spring-security Documentation

Java framework & java repository by @spring-projects. Model Context Protocol (MCP) server & tools with 9.6k stars.

9,599 stars Java Java 1 file · ~22,544 tokens #framework#java#security#spring#spring-framework
RAW Doc

File: docs/modules/ROOT/pages/features/exploits/csrf.adoc

// FIXME: Add links to Servlet and WebFlux support

[[csrf]]
= Cross Site Request Forgery (CSRF)

Spring provides comprehensive support for protecting against https://en.wikipedia.org/wiki/Cross-site_request_forgery[Cross Site Request Forgery (CSRF)] attacks.
In the following sections, we explore:

  • <>
  • <>
  • <>

This portion of the documentation discusses the general topic of CSRF protection. See the relevant sections for specific information on CSRF protection for xref:servlet/exploits/csrf.adoc#servlet-csrf[servlet] and xref:reactive/exploits/csrf.adoc#webflux-csrf[WebFlux] based applications.

[[csrf-explained]]
== 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:

.Transfer form [source,html]

----

The corresponding HTTP request might look like:

.Transfer HTTP request [source]

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:

.Evil transfer form [source,html]

----

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.

Worse yet, this whole process could have been automated by using JavaScript.
This means you did not 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 https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)[XSS attack].
So how do we protect our users from such attacks?

[[csrf-protection]]
== 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 only 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 <>
  • Specifying the <> on your session cookie

[NOTE]

Both protections require that <>.

[[csrf-protection-read-only]]
=== Safe Methods Must be Read-only

For <<csrf-protection,either protection>> against CSRF to work, the application must ensure that https://tools.ietf.org/html/rfc7231#section-4.2.1["safe" HTTP methods are read-only].
This means that requests with the HTTP GET, HEAD, OPTIONS, and TRACE methods should not change the state of the application.

[[csrf-protection-stp]]
=== Synchronizer Token Pattern
The predominant and most comprehensive way to protect against CSRF attacks is to use the https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#synchronizer-token-pattern[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 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 require only the actual CSRF token for each HTTP request that updates the state of the application.
For that to work, our application must ensure that <<csrf-protection-read-only,safe HTTP methods are read-only>>.
This improves usability, since we want to allow linking to our website 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.

Consider how <<csrf-explained,our example>> would change when we use the Synchronizer Token Pattern.
Assume that the actual CSRF token is required to be in an HTTP parameter named _csrf.
Our application's transfer form would look like:

.Synchronizer Token Form [source,html]

----

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:

.Synchronizer Token request [source]

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.

[[csrf-protection-ssa]]
=== SameSite Attribute
An emerging way to protect against <<csrf,CSRF Attacks>> is to specify the https://tools.ietf.org/html/draft-west-first-party-cookies[SameSite Attribute] 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.

[NOTE]

An example, of an HTTP response header with the SameSite attribute might look like:

.SameSite HTTP response [source]

Valid values for the SameSite attribute are:

Consider how <<csrf-explained,our example>> 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 continues to send the JSESSIONID cookie with requests coming from the banking website.
However, the browser no longer sends 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 https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-5[considerations] to be aware of 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 who stays logged into a social media site hosted at https://social.example.com.
The user receives an email at 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.

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 https://developer.mozilla.org/en-US/docs/Web/HTTP/headers/Set-Cookie#Browser_compatibility[support the SameSite attribute].
However, older browsers that are still in use may not.

For this reason, we generally recommend using the SameSite attribute as a defense in depth rather than the sole protection against CSRF attacks.

[[csrf-when]]
== 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 creating a service that is used only by non-browser clients, you likely want to disable CSRF protection.

[[csrf-when-json]]
=== 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 http://blog.opensecurityresearch.com/2012/02/json-csrf-with-parameter-padding.html[CSRF with JSON by using the following form]:

.CSRF with JSON form [source,html]

----

This produces the following JSON structure

.CSRF with JSON request [source,javascript]

{ "amount": 100, "routingNumber": "evilsRoutingNumber", "account": "evilsAccountNumber", "ignore_me": "=test" }

If an application were not validating the Content-Type header, it would be exposed to this exploit.
Depending on the setup, a Spring MVC application that validates the Content-Type could still be exploited by updating the URL suffix to end with .json, as follows:

.CSRF with JSON Spring MVC form [source,html]

----

[[csrf-when-stateless]]
=== CSRF and Stateless Browser Applications
What if my application is stateless?
That does not 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 is sent with the request in the same manner that the JSESSIONID cookie was sent in our previous example.
This application is vulnerable to CSRF attacks.

Applications that use basic authentication are also vulnerable to CSRF attacks.
The application is vulnerable since the browser automatically includes the username and password in any requests in the same manner that the JSESSIONID cookie was sent in our previous example.

[[csrf-considerations]]
== CSRF Considerations
There are a few special considerations to consider when implementing protection against CSRF attacks.

// FIXME: Document rotating the CSRF token at log in to avoid a fixation attack

[[csrf-considerations-login]]
=== Logging In

To protect against https://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests[forging login requests], the login HTTP request should be protected against CSRF attacks.
Protecting against forging login 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 login with the malicious user's credentials.
The victim is now authenticated as the malicious user.
. The malicious user then tricks the victim into visiting the compromised website and entering 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 victim's sensitive information.

A possible complication to ensuring login 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 to log in.
For more information refer to <>.

[[csrf-considerations-logout]]
=== Logging Out

To protect against forging logout requests, the logout HTTP request should be protected against CSRF attacks.
Protecting against forging logout requests is necessary so that a malicious user cannot read a victim's sensitive information.
For details on the attack, see https://labs.detectify.com/2017/03/15/loginlogout-csrf-time-to-reconsider/[this blog post].

A possible complication to ensuring logout 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 have a session to log out.
For more information, see <>.

[[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 does not find an expected CSRF token and rejects the HTTP request.
There are a number of options (each of which come with trade offs) to solve timeouts:

  • 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 lets the expected CSRF token outlive the session.

One might ask why the expected CSRF token is not 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 https://rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails[no longer skips a CSRF checks when the header X-Requested-With is present].
See https://web.archive.org/web/20210221120355/https://lists.webappsec.org/pipermail/websecurity_lists.webappsec.org/2011-February/007533.html[this webappsec.org thread] 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.

// FIXME: Document timeout with lengthy form expire. We do not want to automatically replay that request because it can lead to an exploit.

[[csrf-considerations-multipart]]
=== Multipart (file upload)

Protecting multipart requests (file uploads) from CSRF attacks causes a https://en.wikipedia.org/wiki/Chicken_or_the_egg[chicken or the egg] problem.
To prevent a CSRF attack from occurring, the body of the HTTP request must be read to obtain the actual CSRF token.
However, reading the body means that the file is uploaded, which means an external site can upload a file.

There are three options to using CSRF protection with multipart/form-data:

  • <<csrf-considerations-multipart-header,Include CSRF Token in an HTTP Request Header>>
  • <<csrf-considerations-multipart-body,Place CSRF Token in the Body>>
  • <<csrf-considerations-multipart-url,Place CSRF Token in the URL>>

Each option has its trade-offs.

[NOTE]

Before you integrate Spring Security's CSRF protection with multipart file upload, you should first ensure that you can upload without the CSRF protection. More information about using multipart forms with Spring, see the {spring-framework-reference-url}web/webmvc/mvc-servlet/multipart.html[Multipart Resolver] section of the Spring reference and the {spring-framework-api-url}org/springframework/web/multipart/support/MultipartFilter.html[`MultipartFilter` Javadoc].

[[csrf-considerations-multipart-header]]
==== Include CSRF Token in an HTTP Request Header
When JavaScript is available, you can submit multipart requests by sending the CSRF token in an HTTP request header.
This avoids placing the token in the URL and avoids processing multipart request bodies before CSRF validation.
This is generally the preferred approach for browser applications with JavaScript clients.

See xref:servlet/exploits/csrf.adoc#csrf-integration-javascript-other[JavaScript applications] for Servlet applications and xref:reactive/exploits/csrf.adoc#webflux-csrf-include-ajax[AJAX and JSON Requests] for Reactive applications.

[[csrf-considerations-multipart-body]]
==== Place CSRF Token in the Body
Another option is to include the actual CSRF token in the body of the request.
By placing the CSRF token in the body, the body is read before authorization is performed.
This means that anyone can place temporary files on your server.
However, only authorized users can 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.

[[csrf-considerations-multipart-url]]
==== Include CSRF Token in URL
If letting unauthorized users upload temporary files is not acceptable and JavaScript is not available, 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.
You can find additional information in https://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3[RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI's].

[[csrf-considerations-override-method]]
==== HiddenHttpMethodFilter
Some applications can use a form parameter to override the HTTP method.
For example, the following form can treat the HTTP method as a delete rather than a post.

.CSRF Hidden HTTP Method Form [source,html]

----

Overriding the HTTP method occurs in a filter.
That filter must be placed before Spring Security's support.
Note that overriding happens only on a post, so this is actually unlikely to cause any real problems.
However, it is still best practice to ensure that it is placed before Spring Security's filters.


File: docs/modules/ROOT/pages/features/exploits/headers.adoc

[[headers]]
= Security HTTP Response Headers

[NOTE]

This portion of the documentation discusses the general topic of Security HTTP Response Headers. See the relevant sections for specific information on Security HTTP Response Headers in xref:servlet/exploits/headers.adoc#servlet-headers[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers[WebFlux]-based applications.

You can use https://owasp.org/www-project-secure-headers/#div-headers[HTTP response headers] in many ways to increase the security of web applications.
This section is dedicated to the various HTTP response headers for which Spring Security provides explicit support for.
If necessary, you can also configure Spring Security to provide <<headers-custom,custom headers>>.

[[headers-default]]
== Default Security Headers

[NOTE]

See the relevant sections for how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-default[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-default[webflux]-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:

.Default Security HTTP Response Headers [source,http]

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: 0

[NOTE]

Strict-Transport-Security is added only 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, see the corresponding sections:

  • <<headers-cache-control,Cache Control>>
  • <<headers-content-type-options,Content Type Options>>
  • <<headers-hsts,HTTP Strict Transport Security>>
  • <<headers-frame-options,X-Frame-Options>>
  • <<headers-xss-protection,X-XSS-Protection>>

[[headers-cache-control]]
== Cache Control

[NOTE]

See to the relevant sections for how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-cache-control[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-cache-control[webflux]-based applications.

Spring Security's default is to disable caching to protect the user's content.

If a user authenticates to view sensitive information and then logs out, we do not 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:

.Default Cache Control HTTP Response Headers [source]

Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Expires: 0

To be secure by default, Spring Security adds these headers by default.
However, if your application provides its own cache control headers, Spring Security backs out of the way.
This allows for applications to ensure that static resources (such as CSS and JavaScript) can be cached.

[[headers-content-type-options]]
== Content Type Options

[NOTE]

Refer to the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-content-type-options[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-content-type-options[webflux] based applications.

Historically, browsers, including Internet Explorer, would try to guess the content type of a request by using https://en.wikipedia.org/wiki/Content_sniffing[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.

[NOTE]

There are many additional things one should do (such as only display the document in a distinct domain, ensure Content-Type header is set, sanitize the document, and others) 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 that, 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 (that is, 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 http://webblaze.cs.berkeley.edu/papers/barth-caballero-song.pdf[postscript document that is also a valid JavaScript file] and perform an XSS attack with it.

By default, Spring Security disables content sniffing by adding the following header to HTTP responses:

.nosniff HTTP Response Header [source,http]

X-Content-Type-Options: nosniff

[[headers-hsts]]
== HTTP Strict Transport Security (HSTS)

[NOTE]

Refer to the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-hsts[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-hsts[webflux] based applications.

When you type in your bank's website, do you enter mybank.example.com or do you enter \https://mybank.example.com?
If you omit the https protocol, you are potentially vulnerable to https://en.wikipedia.org/wiki/Man-in-the-middle_attack[Man-in-the-Middle attacks].
Even if the website performs a redirect to \https://mybank.example.com, a malicious user could intercept the initial HTTP request and manipulate the response (for example, redirect to \https://mibank.example.com and steal their credentials).

Many users omit the https protocol, and this is why https://tools.ietf.org/html/rfc6797[HTTP Strict Transport Security (HSTS)] was created.
Once mybank.example.com is added as a https://tools.ietf.org/html/rfc6797#section-5.1[HSTS host], a browser can know ahead of time that any request to mybank.example.com should be interpreted as \https://mybank.example.com.
This greatly reduces the possibility of a Man-in-the-Middle attack occurring.

[NOTE]

In accordance with https://tools.ietf.org/html/rfc6797#section-7.2[RFC6797], the HSTS header is injected only into HTTPS responses. 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 way 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 31536000 seconds in a non-leap year):

.Strict Transport Security HTTP Response Header [source]

Strict-Transport-Security: max-age=31536000 ; includeSubDomains ; preload

The optional includeSubDomains directive instructs the browser that subdomains (such as secure.mybank.example.com) should also be treated as an HSTS domain.

The optional preload directive instructs the browser that the domain should be preloaded in browser as an HSTS domain.
For more details on HSTS preload, see https://hstspreload.org.

[[headers-hpkp]]
== HTTP Public Key Pinning (HPKP)

[NOTE]

https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning[HTTP Public Key Pinning (HPKP)] specifies to a web client which public key to use with a 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 https://www.chromestatus.com/feature/5903385005916160[Chrome has even removed support] for it.

[[headers-hpkp-deprecated]]
For additional details around why HPKP is no longer recommended, read https://blog.qualys.com/ssllabs/2016/09/06/is-http-public-key-pinning-dead[Is HTTP Public Key Pinning Dead?] and https://scotthelme.co.uk/im-giving-up-on-hpkp/[I'm giving up on HPKP].

[[headers-frame-options]]
== X-Frame-Options

[NOTE]

See the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-frame-options[servlet] and xref:reactive/exploits/headers.adoc#webflux-headers-frame-options[webflux] based applications.

Letting your website be added to a frame can be a security issue.
For example, by 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 https://en.wikipedia.org/wiki/Clickjacking[Clickjacking].

[NOTE]

Another modern approach to dealing with clickjacking is to use <>.

There are a number ways to mitigate clickjacking attacks.
For example, to protect legacy browsers from clickjacking attacks, you can use https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Best-for-now_Legacy_Browser_Frame_Breaking_Script[frame breaking code].
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 https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options[X-Frame-Options] header.
By default, Spring Security disables rendering pages within an iframe by using with the following header:

[source]

X-Frame-Options: DENY

[[headers-xss-protection]]
== X-XSS-Protection

[NOTE]

See the relevant sections to see how to customize the defaults for both xref:servlet/exploits/headers.adoc#servlet-headers-xss-protection[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-xss-protection[webflux]-based applications.

Some browsers have built-in support for filtering out https://www.owasp.org/index.php/Testing_for_Reflected_Cross_site_scripting_(OWASP-DV-001)[reflected XSS attacks].
The filter has been deprecated in major browsers, and https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html#x-xss-protection[current OWASP recommendation] is to explicitly set the header to 0.

By default, Spring Security blocks the content by using the following header:

[source]

X-XSS-Protection: 0

[[headers-csp]]
== Content Security Policy (CSP)

[NOTE]

See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-csp[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-csp[webflux]-based applications.

https://www.w3.org/TR/CSP2/[Content Security Policy (CSP)] is a mechanism that web applications can use 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.

[NOTE]

Content Security Policy is not intended to solve all content injection vulnerabilities. Instead, you can use CSP 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 can use 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:

.Content Security Policy Example [source]

Content-Security-Policy: script-src https://trustedscripts.example.com

An attempt to load a script from another source other than what is declared in the script-src directive is blocked by the user-agent.
Additionally, if the https://www.w3.org/TR/CSP2/#directive-report-uri[report-uri] directive is declared in the security policy, the violation will be reported by the user-agent to the declared URL.

For example, if a web application violates the declared security policy, the following response header instructs the user-agent to send violation reports to the URL specified in the policy's report-uri directive.

.Content Security Policy with report-uri [source]

Content-Security-Policy: script-src https://trustedscripts.example.com; report-uri /csp-report-endpoint/

https://www.w3.org/TR/CSP2/#violation-reports[Violation reports] are standard JSON structures that can be captured either by the web application's own API or by a publicly hosted CSP violation reporting service, such as https://report-uri.io/.

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 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 can be loaded from one of two possible sources.

.Content Security Policy Report Only [source]

Content-Security-Policy-Report-Only: script-src 'self' https://trustedscripts.example.com; report-uri /csp-report-endpoint/

If the site violates this policy, by attempting to load a script from evil.example.com, the user-agent sends a violation report to the declared URL specified by the report-uri directive but still lets the violating resource load.

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:

https://www.html5rocks.com/en/tutorials/security/content-security-policy/[An Introduction to Content Security Policy]

https://developer.mozilla.org/en-US/docs/Web/Security/CSP[CSP Guide - Mozilla Developer Network]

https://www.w3.org/TR/CSP2/[W3C Candidate Recommendation]

[[headers-referrer]]
== Referrer Policy

[NOTE]

See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-referrer[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-referrer[webflux]-based applications.

https://www.w3.org/TR/referrer-policy[Referrer Policy] is a mechanism that web applications can use to manage the referrer field, which contains the last
page the user was on.

Spring Security's approach is to use the https://www.w3.org/TR/referrer-policy/[Referrer Policy] header, which provides different https://www.w3.org/TR/referrer-policy/#referrer-policies[policies]:

.Referrer Policy Example [source]

Referrer-Policy: same-origin

The Referrer-Policy response header instructs the browser to let the destination knows the source where the user was previously.

[[headers-feature]]
== Feature Policy

[NOTE]

See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-feature[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-feature[webflux]-based applications.

https://wicg.github.io/feature-policy/[Feature Policy] is a mechanism that lets web developers to selectively enable, disable, and modify the behavior of certain APIs and web features in the browser.

.Feature Policy Example [source]

Feature-Policy: geolocation 'self'

With Feature Policy, developers can opt-in to a set of "policies" for the browser to enforce on specific features used throughout your site.
These policies restrict what APIs the site can access or modify the browser's default behavior for certain features.

[[headers-permissions]]
== Permissions Policy

[NOTE]

See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-permissions[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-permissions[webflux]-based applications.

https://w3c.github.io/webappsec-permissions-policy/[Permissions Policy] is a mechanism that lets web developers selectively enable, disable, and modify the behavior of certain APIs and web features in the browser.

.Permissions Policy Example [source]

Permissions-Policy: geolocation=(self)

With Permissions Policy, developers can opt-in to a set of "policies" for the browser to enforce on specific features used throughout your site.
These policies restrict what APIs the site can access or modify the browser's default behavior for certain features.

[[headers-clear-site-data]]
== Clear Site Data

[NOTE]

See the relevant sections to see how to configure both xref:servlet/exploits/headers.adoc#servlet-headers-clear-site-data[servlet]- and xref:reactive/exploits/headers.adoc#webflux-headers-clear-site-data[webflux]- based applications.

https://www.w3.org/TR/clear-site-data/[Clear Site Data] is a mechanism by which any browser-side data (cookies, local storage, and the like) can be removed when an HTTP response contains this header:

[source]

Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"

This is a nice clean-up action to perform on logout.

[[headers-custom]]
== Custom Headers

[NOTE]

See the relevant section to see how to configure xref:servlet/exploits/headers.adoc#servlet-headers-custom[servlet] 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.


File: docs/modules/ROOT/pages/features/exploits/http.adoc

[[http]]
= HTTP

All HTTP-based communication, including https://www.troyhunt.com/heres-why-your-static-website-needs-https/[static resources], should be protected by https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html[using TLS].

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.

[[http-redirect]]
== Redirect to HTTPS

When a client uses HTTP, you can configure Spring Security to redirect to HTTPS in both xref:servlet/exploits/http.adoc#servlet-http-redirect[Servlet] and xref:reactive/exploits/http.adoc#webflux-http-redirect[WebFlux] environments.

[[http-hsts]]
== Strict Transport Security

Spring Security provides support for xref:features/exploits/headers.adoc#headers-hsts[Strict Transport Security] and enables it by default.

[[http-proxy-server]]
== Proxy Server Configuration

When using a proxy server, it is important to ensure that you have configured your application properly.
For example, many applications have a load balancer that responds to request for \https://example.com/ by forwarding the request to an application server at \https://192.168.0.107
Without proper configuration, the application server can not know that the load balancer exists and treats the request as though \https://192.168.0.107:8080 was requested by the client.

To fix this, the proxy needs to pass on the details of the original request, and the application needs to be configured to use them.
Two kinds of headers are used for this, and it is important to know which of them applies in your deployment:

  • The standard Forwarded header, defined by https://tools.ietf.org/html/rfc7239[RFC 7239], which carries the original host, protocol, and client in a single header.
  • The non-standard X-Forwarded-* headers, such as X-Forwarded-Host, X-Forwarded-Proto, and X-Forwarded-For, which predate RFC 7239.

Most proxies still send the X-Forwarded-* headers rather than the standard Forwarded header, while Spring Framework and servers such as Reactor Netty and Jetty understand both.
Do not assume that only one of them is in use.

[NOTE]

Both kinds of headers are supplied by the client unless a proxy overwrites them, so an application that trusts them without a trusted proxy in front of it can be made to believe a request arrived over a different host, protocol, or client address than it really did.

For this reason, the proxy at the edge of your network must be configured to remove or overwrite any forwarded headers that arrive from the outside, for both kinds of headers.
Dropping only the Forwarded header while passing through X-Forwarded-* (or the reverse) leaves the application open to the same spoofing through the other set.
Only headers added by a proxy you control should reach the application.

Once untrusted values are handled at the edge, the application server can be configured to apply the headers.
For example, Tomcat uses https://tomcat.apache.org/tomcat-10.1-doc/api/org/apache/catalina/valves/RemoteIpValve.html[`RemoteIpValve`] and Jetty uses https://eclipse.dev/jetty/javadoc/jetty-11/org/eclipse/jetty/server/ForwardedRequestCustomizer.html[`ForwardedRequestCustomizer`].
Alternatively, Spring users can use {spring-framework-reference-url}web/webmvc/filters.html#filters-forwarded-headers[ForwardedHeaderFilter] with the Servlet stack or {spring-framework-reference-url}web/webflux/reactive-spring.html#webflux-forwarded-headers[ForwardedHeaderTransformer] with the Reactive stack.
Both handle the Forwarded header and the X-Forwarded-* headers, and both can be configured to remove the headers instead of applying them, which is useful when the application is not behind a proxy.

Spring Boot users can use the server.forward-headers-strategy property to configure the application.
See the {spring-boot-reference-url}how-to/webserver.html#howto.webserver.use-behind-a-proxy-server[Spring Boot documentation] for further details.


File: docs/modules/ROOT/pages/features/exploits/index.adoc

[[exploits]]
= Protection Against Exploits
:page-section-summary-toc: 1

Spring Security provides protection against common exploits.
Whenever possible, the protection is enabled by default.
This section describes the various exploits that Spring Security protects against.


File: docs/modules/ROOT/pages/features/authorization/index.adoc

[[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/authorize-http-requests.adoc[Servlet] and xref:reactive/authorization/authorize-http-requests.adoc[WebFlux] environments.

[[authorization-method]]
== Method Based Authorization

Spring Security provides authorization based on the method invocation for both xref:servlet/authorization/method-security.adoc[Servlet] and xref:reactive/authorization/method.adoc[WebFlux] environments.


File: docs/modules/ROOT/pages/features/authentication/index.adoc

[[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] and xref:reactive/authentication/index.adoc[WebFlux] for details on what is supported for each stack.


File: docs/modules/ROOT/pages/features/authentication/password-storage.adoc

[[authentication-password-storage]]
= Password Storage

Spring Security's PasswordEncoder interface is used to perform a one-way transformation of a password to let the password be stored securely.
Given PasswordEncoder is a one-way transformation, it is not useful when the password transformation needs to be two-way (such as 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 plaintext.
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 by using attacks such as SQL Injection.
As more and more user credentials became public, security experts realized that 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, 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 user's password.
The salt and the user's password would be run through the hash function to produce 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-intensive (they intentionally use a lot of CPU, memory, or other resources).
An adaptive one-way function allows configuring a "work factor" that can grow as hardware gets better.
We recommend that the "work factor" be tuned to take about one 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 that it puts excessive burden on your own system or irritates users.
Spring Security has attempted to provide a good starting point for the "work factor", but we encourage users to customize the "work factor" for their own system, since the performance varies drastically from system to system.
Examples of adaptive one-way functions that should be used include <<authentication-password-storage-bcrypt,bcrypt>>, <<authentication-password-storage-pbkdf2,PBKDF2>>, <<authentication-password-storage-scrypt,scrypt>>, and <<authentication-password-storage-argon2,argon2>>.

Because adaptive one-way functions are intentionally resource intensive, validating a username and password for every request can significantly degrade the performance of an application.
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 (that is, username and password) for a short term credential (such as a session, and OAuth Token, and so on).
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 on the <<authentication-password-storage-history,Password History>> section, you might expect that the default PasswordEncoder would now be something like BCryptPasswordEncoder.
However, this ignores three real world problems:

  • Many applications use 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 by 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 by using PasswordEncoderFactories:

.Create Default DelegatingPasswordEncoder
include-code::./DelegatingPasswordEncoderUsage[tag=createDefaultPasswordEncoder,indent=0]

Alternatively, you can create your own custom instance:

.Create Custom DelegatingPasswordEncoder
include-code::./DelegatingPasswordEncoderUsage[tag=createCustomPasswordEncoder,indent=0]

[[authentication-password-storage-dpe-format]]
=== Password Storage Format

The general format for a password is:

.DelegatingPasswordEncoder Storage Format [source,text,attrs="-attributes"]

{id}encodedPassword

id is an identifier that is used to look up which PasswordEncoder should be used and encodedPassword is the original encoded password for the selected PasswordEncoder.
The id must be at the beginning of the password, start with {, and end with }.
If the id cannot be found, the id is set to null.
For example, the following might be a list of passwords encoded using different id values.
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 has a PasswordEncoder id of bcrypt and an encodedPassword value of $2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG.
When matching, it would delegate to BCryptPasswordEncoder
<2> The second password has a PasswordEncoder id of noop and encodedPassword value of password.
When matching, it would delegate to NoOpPasswordEncoder
<3> The third password has a PasswordEncoder id of pbkdf2 and encodedPassword value of 5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc.
When matching, it would delegate to Pbkdf2PasswordEncoder
<4> The fourth password has a PasswordEncoder id of scrypt and encodedPassword value of $e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=
When matching, it would delegate to SCryptPasswordEncoder
<5> The final password has a PasswordEncoder id of sha256 and encodedPassword value 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 is used for encoding passwords.
In the DelegatingPasswordEncoder we constructed earlier, that means that the result of encoding password is delegated to BCryptPasswordEncoder and be prefixed with +{bcrypt}+.
The end result looks like the following example:

.DelegatingPasswordEncoder Encode Example [source,text,attrs="-attributes"]

{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG

[[authentication-password-storage-dpe-matching]]
=== Password Matching

Matching is based upon the +{id}+ and the mapping of the id to the PasswordEncoder provided in the constructor.
Our example in <<authentication-password-storage-dpe-format,Password Storage 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) results in an IllegalArgumentException.
This behavior can be customized by using DelegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(PasswordEncoder).

By using the id, we can match on any password encoding but encode passwords by 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 is 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
include-code::./WithDefaultPasswordEncoderUsage[tag=createSingleUser,indent=0]

If you are creating multiple users, you can also reuse the builder:

.withDefaultPasswordEncoder Reusing the Builder
include-code::./WithDefaultPasswordEncoderUsage[tag=createMultipleUsers,indent=0]

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,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-reference-url}cli/index.html[Spring Boot CLI].

For example, the following example encodes 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 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 <<authentication-password-storage-configuration,exposing a NoOpPasswordEncoder bean>>.

Alternatively, you can prefix all of your passwords with the correct id and continue to use DelegatingPasswordEncoder.
For example, if you are using BCrypt, you would migrate your password from something like:


$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG

to

[source,attrs="-attributes"]

{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG

For a complete listing of the mappings, see the Javadoc for javadoc:org.springframework.security.crypto.factory.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.
To make it more resistant 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 javadoc:org.springframework.security.crypto.bcrypt.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
include-code::./BCryptPasswordEncoderUsage[tag=bcryptPasswordEncoder,indent=0]

[[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].
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
include-code::./Argon2PasswordEncoderUsage[tag=argon2PasswordEncoder,indent=0]

[[authentication-password-storage-pbkdf2]]
== Pbkdf2PasswordEncoder

The Pbkdf2PasswordEncoder implementation uses the https://en.wikipedia.org/wiki/PBKDF2[PBKDF2] algorithm to hash the passwords.
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
include-code::./Pbkdf2PasswordEncoderUsage[tag=pbkdf2PasswordEncoder,indent=0]

[[authentication-password-storage-scrypt]]
== SCryptPasswordEncoder

The SCryptPasswordEncoder implementation uses the https://en.wikipedia.org/wiki/Scrypt[scrypt] algorithm to hash the passwords.
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
include-code::./SCryptPasswordEncoderUsage[tag=sCryptPasswordEncoder,indent=0]

[[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.

[[password4j]]
== Password4j-based Password Encoders

Spring Security 7.0 introduces alternative password encoder implementations based on the https://github.com/Password4j/password4j[Password4j] library.
These encoders provide additional options for popular hashing algorithms and can be used as alternatives to the existing Spring Security implementations.

The Password4j library is a Java cryptographic library that focuses on password hashing with support for multiple algorithms.
These encoders are particularly useful when you need specific algorithm configurations or want to leverage Password4j's optimizations.

All Password4j-based encoders are thread-safe and can be shared across multiple threads.

[[password4j-argon2]]
=== Argon2Password4jPasswordEncoder

The Argon2Password4jPasswordEncoder implementation uses the https://en.wikipedia.org/wiki/Argon2[Argon2] algorithm via the Password4j library to hash passwords.
This provides an alternative to Spring Security's built-in Argon2PasswordEncoder with different configuration options and potential performance characteristics.

Argon2 is the winner of the https://en.wikipedia.org/wiki/Password_Hashing_Competition[Password Hashing Competition] and is recommended for new applications.
This implementation leverages Password4j's Argon2 support which properly includes the salt in the output hash.

Create an encoder with default settings:

.Argon2Password4jPasswordEncoder
include-code::./Argon2UsageTests[tag=default-params,indent=0]

Create an encoder with custom Argon2 parameters:

.Argon2Password4jPasswordEncoder Custom
include-code::./Argon2UsageTests[tag=custom-params,indent=0]

[[password4j-bcrypt]]
=== BcryptPassword4jPasswordEncoder

The BcryptPassword4jPasswordEncoder implementation uses the https://en.wikipedia.org/wiki/Bcrypt[BCrypt] algorithm via the Password4j library to hash passwords.
This provides an alternative to Spring Security's built-in BCryptPasswordEncoder with Password4j's implementation characteristics.

BCrypt is a well-established password hashing algorithm that includes built-in salt generation and is resistant to rainbow table attacks.
This implementation leverages Password4j's BCrypt support which properly includes the salt in the output hash.

Create an encoder with default settings:

.BcryptPassword4jPasswordEncoder
include-code::./BcryptUsageTests[tag=default-params,indent=0]

Create an encoder with custom bcrypt parameters:

.BcryptPassword4jPasswordEncoder Custom
include-code::./BcryptUsageTests[tag=custom-params,indent=0]

[[password4j-scrypt]]
=== ScryptPassword4jPasswordEncoder

The ScryptPassword4jPasswordEncoder implementation uses the https://en.wikipedia.org/wiki/Scrypt[SCrypt] algorithm via the Password4j library to hash passwords.
This provides an alternative to Spring Security's built-in SCryptPasswordEncoder with Password4j's implementation characteristics.

SCrypt is a memory-hard password hashing algorithm designed to be resistant to hardware brute-force attacks.
This implementation leverages Password4j's SCrypt support which properly includes the salt in the output hash.

Create an encoder with default settings:

.ScryptPassword4jPasswordEncoder
include-code::./ScryptUsageTests[tag=default-params,indent=0]

Create an encoder with custom scrypt parameters:

.ScryptPassword4jPasswordEncoder Custom
include-code::./ScryptUsageTests[tag=custom-params,indent=0]

[[password4j-pbkdf2]]
=== Pbkdf2Password4jPasswordEncoder

The Pbkdf2Password4jPasswordEncoder implementation uses the https://en.wikipedia.org/wiki/PBKDF2[PBKDF2] algorithm via the Password4j library to hash passwords.
This provides an alternative to Spring Security's built-in Pbkdf2PasswordEncoder with explicit salt management.

PBKDF2 is a key derivation function designed to be computationally expensive to thwart dictionary and brute force attacks.
This implementation handles salt management explicitly since Password4j's PBKDF2 implementation does not include the salt in the output hash.
The encoded password format is: +{salt}:{hash}+ where both salt and hash are Base64 encoded.

Create an encoder with default settings:

.Pbkdf2Password4jPasswordEncoder
include-code::./Pbkdf2UsageTests[tag=default-params,indent=0]

Create an encoder with custom PBKDF2 parameters:

.Pbkdf2Password4jPasswordEncoder Custom
include-code::./Pbkdf2UsageTests[tag=custom-params,indent=0]

[[password4j-ballooning]]
=== BalloonHashingPassword4jPasswordEncoder

The BalloonHashingPassword4jPasswordEncoder implementation uses the Balloon hashing algorithm via the Password4j library to hash passwords.
Balloon hashing is a memory-hard password hashing algorithm designed to be resistant to both time-memory trade-off attacks and side-channel attacks.

This implementation handles salt management explicitly since Password4j's Balloon hashing implementation does not include the salt in the output hash.
The encoded password format is: +{salt}:{hash}+ where both salt and hash are Base64 encoded.

Create an encoder with default settings:

.BalloonHashingPassword4jPasswordEncoder
include-code::./BallooningHashingUsageTests[tag=default-params,indent=0]

Create an encoder with custom parameters:

.BalloonHashingPassword4jPasswordEncoder Custom
include-code::./BallooningHashingUsageTests[tag=custom-params,indent=0]

[[authentication-password-storage-configuration]]
== Password Storage Configuration

Spring Security uses <> by default.
However, you can customize this 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 [tabs]

Java:: + [source,java,role="primary"]

@Bean
public static NoOpPasswordEncoder 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 [tabs]

Java:: + [source,java,role="primary"]

http
.passwordManagement(Customizer.withDefaults())


XML:: + [source,xml,role="secondary"]

sec:password-management/


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 [tabs]

Java:: + [source,java,role="primary"]

http
.passwordManagement((management) -> management
.changePasswordPage("/update-password")
)


XML:: + [source,xml,role="secondary"]

<sec:password-management change-password-page="/update-password"/>


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.

[[authentication-compromised-password-check]]
== Compromised Password Checking

There are some scenarios where you need to check whether a password has been compromised, for example, if you are creating an application that deals with sensitive data, it is often needed that you perform some check on user's passwords in order to assert its reliability.
One of these checks can be if the password has been compromised, usually because it has been found in a https://wikipedia.org/wiki/Data_breach[data breach].

To facilitate that, Spring Security provides integration with the https://haveibeenpwned.com/API/v3#PwnedPasswords[Have I Been Pwned API] via the javadoc:org.springframework.security.web.authentication.password.HaveIBeenPwnedRestApiPasswordChecker[] implementation of the javadoc:org.springframework.security.authentication.password.CompromisedPasswordChecker[] interface.

You can either use the CompromisedPasswordChecker API by yourself or, if you are using xref:servlet/authentication/passwords/dao-authentication-provider.adoc[the DaoAuthenticationProvider] via xref:servlet/authentication/passwords/index.adoc[Spring Security authentication mechanisms], you can provide a CompromisedPasswordChecker bean, and it will be automatically picked up by Spring Security configuration.

By doing that, when you try to authenticate via Form Login using a weak password, let's say 123456, you will receive a 401 or be redirected to the /login?error page (depending on your user-agent).
However, just a 401 or the redirect is not so useful in that case, it will cause some confusion because the user provided the right password and still was not allowed to log in.
In such cases, you can handle the CompromisedPasswordException via the AuthenticationFailureHandler to perform your desired logic, like redirecting the user-agent to /reset-password, for example:

.Using CompromisedPasswordChecker
include-code::./CompromisedPasswordCheckerUsage[tag=configuration,indent=0]


File: docs/modules/ROOT/pages/features/integrations/concurrency.adoc

[[concurrency]]
= 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 xref:servlet/integrations/servlet-api.adoc#servletapi-start-runnable[AsyncContext.start(Runnable)] and xref:servlet/integrations/mvc.adoc#mvc-async[Spring MVC Async Integration].

== 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:

[tabs]

Java:: + [source,java,role="primary"]

public void run() {
try {
SecurityContextHolder.setContext(securityContext);
delegate.run();
} finally {
SecurityContextHolder.clearContext();
}

}

Kotlin:: + [source,kotlin,role="secondary"]

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 xref:servlet/appendix/namespace/method-security.adoc#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:

[tabs]

Java:: + [source,java,role="primary"]

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:: + [source,kotlin,role="secondary"]

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:

[tabs]

Java:: + [source,java,role="primary"]

Runnable originalRunnable = new Runnable() {
public void run() {
// invoke secured service
}
};

DelegatingSecurityContextRunnable wrappedRunnable =
new DelegatingSecurityContextRunnable(originalRunnable);

new Thread(wrappedRunnable).start();

Kotlin:: + [source,kotlin,role="secondary"]

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:

[tabs]

Java:: + [source,java,role="primary"]

SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication authentication =
UsernamePasswordAuthenticationToken.authenticated("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:: + [source,kotlin,role="secondary"]

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 Runnables
  • 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.

[tabs]

Java:: + [source,java,role="primary"]

@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:: + [source,kotlin,role="secondary"]

@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:

[tabs]

Java:: + [source,java,role="primary"]

SimpleAsyncTaskExecutor delegateExecutor = new SimpleAsyncTaskExecutor();
DelegatingSecurityContextExecutor executor =
new DelegatingSecurityContextExecutor(delegateExecutor);


Kotlin:: + [source,kotlin,role="secondary"]

val delegateExecutor = SimpleAsyncTaskExecutor() val executor = DelegatingSecurityContextExecutor(delegateExecutor)

======

Now anytime executor.execute(Runnable) is executed the SecurityContext is first obtained by the SecurityContextHolder and then that SecurityContext is used to create our DelegatingSecurityContextRunnable.
This means that we are running our Runnable with the same user that was used to invoke the executor.execute(Runnable) code.

== 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

File: docs/modules/ROOT/pages/features/integrations/cryptography.adoc

[[crypto]]
= Spring Security Crypto Module

[[spring-security-crypto-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.

[[spring-security-crypto-encryption]]
== Encryptors
Spring Security provides javadoc:org.springframework.security.crypto.encrypt.AesGcmBytesEncryptor[] and javadoc:org.springframework.security.crypto.encrypt.AesCbcBytesEncryptor[] for constructing symmetric encryptors.
These can be used to encrypt data in raw byte[] form.
You can also construct javadoc:org.springframework.security.crypto.encrypt.TextEncryptor[] instances to encrypt text strings.
Encryptors are thread-safe.

[NOTE]

Both `BytesEncryptor` and `TextEncryptor` are interfaces. `BytesEncryptor` has multiple implementations.

[[spring-security-crypto-encryption-bytes]]
=== BytesEncryptor
Use AesGcmBytesEncryptor to construct a BytesEncryptor with authenticated encryption:

.BytesEncryptor [tabs]

Java:: + [source,java,role="primary"]

AesGcmBytesEncryptor.withPassword("password", "salt").build();

Kotlin:: + [source,kotlin,role="secondary"]

AesGcmBytesEncryptor.withPassword("password", "salt").build()

======

AesGcmBytesEncryptor uses 256-bit AES encryption with Galois Counter Mode (GCM), providing https://en.wikipedia.org/wiki/Authenticated_encryption[authenticated encryption] (AEAD).
It derives the secret key using PKCS #5's PBKDF2 (Password-Based Key Derivation Function #2).
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.
You can generate such a salt by using a KeyGenerator:

.Generating a key [tabs]

Java:: + [source,java,role="primary"]

String salt = KeyGenerators.string().generateKey(); // generates a random 8-byte salt that is then hex-encoded

Kotlin:: + [source,kotlin,role="secondary"]

val salt = KeyGenerators.string().generateKey() // generates a random 8-byte salt that is then hex-encoded

======

Users who require CBC mode may use AesCbcBytesEncryptor:

.AesCbcBytesEncryptor [tabs]

Java:: + [source,java,role="primary"]

AesCbcBytesEncryptor.withPassword("password", "salt").build();

Kotlin:: + [source,kotlin,role="secondary"]

AesCbcBytesEncryptor.withPassword("password", "salt").build()

======

This mode is not https://en.wikipedia.org/wiki/Authenticated_encryption[authenticated] and does not provide any
guarantees about the authenticity of the data.
For a more secure alternative, users should prefer AesGcmBytesEncryptor.

[[spring-security-crypto-encryption-text]]
=== TextEncryptor
Use AesCbcBytesEncryptor to encrypt text data:

.TextEncryptor [tabs]

Java:: + [source,java,role="primary"]

AesCbcBytesEncryptor.withPassword("password", "salt").build();

Kotlin:: + [source,kotlin,role="secondary"]

AesCbcBytesEncryptor.withPassword("password", "salt").build()

======

AesCbcBytesEncryptor encrypts data as raw bytes.
You can hex-encode the result for easy storage on the filesystem or in the database.

NOTE: Queryable text encryption (encrypting such that the same plaintext always produces the same ciphertext) is no longer recommended, as it relies on a fixed initialization vector and does not provide adequate security.
Instead, look to your data store for a mechanism to query encrypted data.

[[spring-security-crypto-keygenerators]]
== Key Generators
The javadoc:org.springframework.security.crypto.keygen.KeyGenerators[] class provides a number of convenience factory methods for constructing different types of key generators.
By using this class, you can create a javadoc:org.springframework.security.crypto.keygen.BytesKeyGenerator[] to generate byte[] keys.
You can also construct a javadoc:org.springframework.security.crypto.keygen.StringKeyGenerator[] to generate string keys.
KeyGenerators is a thread-safe class.

=== BytesKeyGenerator
You can use the KeyGenerators.secureRandom factory methods to generate a BytesKeyGenerator backed by a SecureRandom instance:

.BytesKeyGenerator [tabs]

Java:: + [source,java,role="primary"]

BytesKeyGenerator generator = KeyGenerators.secureRandom(); byte[] key = generator.generateKey();

Kotlin:: + [source,kotlin,role="secondary"]

val generator = KeyGenerators.secureRandom() val key = generator.generateKey()

======

The default key length is 8 bytes.
A KeyGenerators.secureRandom variant provides control over the key length:

.KeyGenerators.secureRandom [tabs]

Java:: + [source,java,role="primary"]

KeyGenerators.secureRandom(16);

Kotlin:: + [source,kotlin,role="secondary"]

KeyGenerators.secureRandom(16)

======

Use the KeyGenerators.shared factory method to construct a BytesKeyGenerator that always returns the same key on every invocation:

.KeyGenerators.shared [tabs]

Java:: + [source,java,role="primary"]

KeyGenerators.shared(16);

Kotlin:: + [source,kotlin,role="secondary"]

KeyGenerators.shared(16)

======

=== StringKeyGenerator
You can use the KeyGenerators.string factory method to construct an 8-byte, SecureRandom KeyGenerator that hex-encodes each key as a String:

.StringKeyGenerator [tabs]

Java:: + [source,java,role="primary"]

KeyGenerators.string();

Kotlin:: + [source,kotlin,role="secondary"]

KeyGenerators.string()

======

[[spring-security-crypto-passwordencoders]]
== Password Encoding
The password package of the spring-security-crypto module provides support for encoding passwords.
PasswordEncoder is the central service interface and has the following signature:

[source,java]

public interface PasswordEncoder {
String encode(CharSequence rawPassword);

text
boolean matches(CharSequence rawPassword, String encodedPassword);

default boolean upgradeEncoding(String encodedPassword) {
	return false;
}

}

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, to hinder password crackers.
You can tune the amount of work it does by using the strength parameter, which takes a value 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.
The following example uses the BCryptPasswordEncoder:

.BCryptPasswordEncoder [tabs]

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))

======

The Pbkdf2PasswordEncoder implementation uses PBKDF2 algorithm to hash the passwords.
To defeat password cracking, PBKDF2 is a deliberately slow algorithm and should be tuned to take about .5 seconds to verify a password on your system.
The following system uses the Pbkdf2PasswordEncoder:

.Pbkdf2PasswordEncoder [tabs]

Java:: + [source,java,role="primary"]

// Create an encoder with all the defaults Pbkdf2PasswordEncoder encoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8(); 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.defaultsForSpringSecurity_v5_8() val result: String = encoder.encode("myPassword") assertTrue(encoder.matches("myPassword", result))

======