mkdir -p docs/modules/ROOT/
mkdir -p docs/modules/ROOT/pages/
git checkout antora-2.x docs/antora.yml
git checkout antora-2.x docs/modules/ROOT/nav.adoc
mv docs/manual/src/docs/asciidoc/images docs/modules/ROOT/
mv docs/manual/src/docs/asciidoc/_includes/* docs/modules/ROOT/pages/
cp ~/code/rwinch/spring-reference/*antora* ~/code/spring-projects/spring-security/
mv docs/modules/ROOT/pages/about docs/modules/ROOT/pages/overview
This commit is contained in:
Rob Winch 2021-07-26 15:48:55 -05:00
parent 7b73b94198
commit f01a13aa52
218 changed files with 119 additions and 1441 deletions

24
docs/antora.yml Normal file
View File

@ -0,0 +1,24 @@
name: security
title: Spring Security
version: 5.6
start_page: ROOT:overview/index.adoc
asciidoc:
attributes:
page-pagination: true
idprefix: ''
idseparator: '-'
apacheds-core-version: 1.5.5
figures: servlet/architecture
gh-old-samples-url: https://github.com/spring-projects/spring-security/tree/5.4.x/samples
gh-samples-url: https://github.com/spring-projects/spring-security-samples/tree/main
gh-url: https://github.com/spring-projects/spring-security/tree/main
icondir: icons
security-api-url: https://docs.spring.io/spring-security/site/docs/current/api/
security-reference-url: https://docs.spring.io/spring-security/site/docs/reference/html5/
spring-core-version: 5.3.8
spring-framework-api-url: https://docs.spring.io/spring-framework/docs/current/javadoc-api/
spring-framework-reference-url: https://docs.spring.io/spring-framework/docs/current/reference/html/
spring-security-version: 5.6.0
unboundid-ldapsdk-version: 4.1
nav:
- modules/ROOT/nav.adoc

View File

@ -1,40 +0,0 @@
apply plugin: 'org.asciidoctor.jvm.convert'
apply plugin: 'io.spring.convention.repository'
asciidoctor {
baseDir = file('src/docs/asciidoc')
options eruby: 'erubis'
def ghSamplesUrl = "https://github.com/spring-projects/spring-security-samples/tree/$samplesBranch"
attributes copycss : '',
icons : 'font',
'source-highlighter': 'prettify',
sectanchors : '',
toc: '',
'toc-placement' : 'preamble',
idprefix: '',
idseparator: '-',
doctype: 'book',
'spring-security-version' : project.version,
'include-maven-repository' : getMavenRepositoryInclude(),
revnumber : project.version,
'gh-samples-url': ghSamplesUrl,
'gh-old-samples-url': "https://github.com/spring-projects/spring-security/tree/5.4.x/samples"
}
ext.spec = copySpec {
into ('guides') {
from(asciidoctor.outputDir)
exclude 'build', 'Guardfile'
}
}
def getMavenRepositoryInclude() {
if(snapshotBuild) {
return "_includes/maven-repository-snapshot.asc"
} else if(releaseBuild) {
return "_includes/maven-repository-release.asc"
} else {
return "_includes/maven-repository-milestone.asc"
}
}

View File

@ -1,15 +0,0 @@
require 'asciidoctor'
require 'erb'
guard 'shell' do
watch(/^.*\.asc$/) {|m|
Asciidoctor.render_file(m[0], :to_dir => "build/", :safe => Asciidoctor::SafeMode::UNSAFE, :attributes=> {'toc' => '', 'idprefix' => '', 'idseparator' => '-', 'copycss' => '', 'icons' => 'font', 'source-highlighter' => 'prettify', 'sectanchors' => '', 'toc-placement' => 'preamble', 'revnumber' => '3.2.0.CI-SNAPSHOT',
'spring-security-version' => '3.2.0.CI-SNAPSHOT',
'download-url' => 'https://github.com/spring-projects/spring-security/archive/main.zip',
'include-maven-repository' => '_includes/maven-repository-snapshot.asc' })
}
end
guard 'livereload' do
watch(%r{build/.+\.(css|js|html)$})
end

View File

@ -1,6 +0,0 @@
Verify the application is working:
* Navigate to http://localhost:8080/sample/ You should see a login form
* Enter the *username* _user_, the *password* _password_, and click the *Login* button. You should now see the main application.
* Try clicking on the Compose link and creating a message. The message details should be displayed.
* Now click on the Inbox link and see the message listed. You can click on the summary link to see the details displayed again.

View File

@ -1,21 +0,0 @@
=== Exploring the secured application
Start the application as we did in <<running-the-{starter-appname}-application>>
Navigate to http://localhost:8080/ and click on the *_secured pages_* link and you will be prompted to login.
==== Authenticating to the secured application
Try entering an invalid username and password:
* *Username* _invalid_
* *Password* _invalid_
You should see an error message stating that authentication failed. Now try entering a valid username and password:
* *Username* _user_
* *Password* _password_
You should now see the page that we wanted to secure.
NOTE: The reason we can successfully authenticate with *Username* _user_ and *Password* _password_ is because that is what we configured in our <<security-config-java,SecurityConfig>>.

View File

@ -1,19 +0,0 @@
=== Exploring the secured application
Start the server as we did in <<running-the-{starter-appname}-application>> Now when you visit http://localhost:8080/sample/ you will be prompted with a login page that is automatically generated by Spring Security.
==== Authenticating to the secured application
Try entering an invalid username and password:
* *Username* _invalid_
* *Password* _invalid_
You should see an error message stating that authentication failed. Now try entering a valid username and password:
* *Username* _user_
* *Password* _password_
You should now see the page that we wanted to secure.
NOTE: The reason we can successfully authenticate with *Username* _user_ and *Password* _password_ is because that is what we configured in our <<security-config-java,SecurityConfig>>.

View File

@ -1,19 +0,0 @@
=== Exploring the secured application
Start the server as we did in <<running-the-{starter-appname}-application>> Now when you visit http://localhost:8080/sample/ you will be prompted with a login page that is automatically generated by Spring Security.
==== Authenticating to the secured application
Try entering an invalid username and password:
* *Username* _invalid_
* *Password* _invalid_
You should see an error message stating that authentication failed. Now try entering a valid username and password:
* *Username* _user_
* *Password* _password_
You should now see the page that we wanted to secure.
NOTE: The reason we can successfully authenticate with *Username* _user_ and *Password* _password_ is because that is what we configured in our <<security-config-xml,security-config-xml>>.

View File

@ -1,118 +0,0 @@
== Securing the application
Before securing the application, it is important to ensure that the existing application works as we did in <<running-the-{starter-appname}-application>>. Now that the application runs without security, we are ready to add security to our application. This section demonstrates the minimal steps to add Spring Security to our application.
=== Updating your dependencies
include::../{include-maven-repository}[]
In order to use Spring Security you must add the necessary dependencies. For the sample we will add the following Spring Security dependencies:
.pom.xml
[source,xml]
[subs="verbatim,attributes"]
----
<dependencies>
<!-- ... other dependency elements ... -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>{spring-security-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>{spring-security-version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId> <1>
<version>2.1.2.RELEASE</version>
</dependency>
</dependencies>
----
<1> We are using https://www.thymeleaf.org/[Thymeleaf] for our view template engine
and need to add an additional dependency for the https://github.com/thymeleaf/thymeleaf-extras-springsecurity[Thymeleaf - Spring Security integration module].
After you have completed this, you need to ensure that STS knows about the updated dependencies by:
* Right click on the _spring-security-samples-{starter-config-type}-{starter-appname}_ application
* Select *Maven->Update project...*
* Ensure the project is selected, and click *OK*
=== Creating your Spring Security configuration
The next step is to create a Spring Security configuration.
* Right click the _spring-security-samples-{starter-config-type}-{starter-appname}_ project in the Package Explorer view
* Select *New->Class*
* Enter _org.springframework.security.samples.config_ for the *Package*
* Enter _SecurityConfig_ for the *Name*
* Click *Finish*
* Replace the file with the following contents:
[[security-config-java]]
.src/main/java/org/springframework/security/samples/config/SecurityConfig.java
[source,java]
----
package org.springframework.security.samples.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/index").permitAll() <1>
.antMatchers("/user/**").hasRole("USER") <2>
.and()
.formLogin()
.loginPage("/login").failureUrl("/login-error"); <3>
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
----
<1> requests matched against _/css/**_ and _/index_ are fully accessible
<2> requests matched against _/user/**_ require a user to be authenticated and must be associated to the _USER_ role
<3> form-based authentication is enabled with a custom login page and failure url
NOTE: The name of the configureGlobal method is not important. However, it is important to only configure AuthenticationManagerBuilder in a class annotated with either `@EnableWebSecurity`, `@EnableGlobalMethodSecurity`, or `@EnableGlobalAuthentication`. Doing otherwise has unpredictable results.
[[servlet-api-integration]]
The <<security-config-java,SecurityConfig>> will:
* Require authentication to requests matched against _/user/**_
* Specifies the URL to send users to for form-based login
* Allow the user with the *Username* _user_ and the *Password* _password_ to authenticate with form based authentication
* Allow the user to logout
* 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()]

View File

@ -1,92 +0,0 @@
== Securing the application
Before securing your application, it is important to ensure that the existing application works as we did in <<running-the-{starter-appname}-application>>. Now that the application runs without security, we are ready to add security to our application. This section demonstrates the minimal steps to add Spring Security to our application.
=== Updating your dependencies
include::../{include-maven-repository}[]
In order to use Spring Security you must add the necessary dependencies. For the sample we will add the following Spring Security dependencies:
.pom.xml
[source,xml]
[subs="verbatim,attributes"]
----
<dependencies>
<!-- ... other dependency elements ... -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>{spring-security-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>{spring-security-version}</version>
</dependency>
</dependencies>
----
After you have completed this, you need to ensure that STS knows about the updated dependencies by:
* Right click on the _spring-security-samples-{starter-config-type}-{starter-appname}_ application
* Select *Maven->Update project...*
* Ensure the project is selected, and click *OK*
=== Creating your Spring Security configuration
The next step is to create a Spring Security configuration.
* Right click the _spring-security-samples-{starter-config-type}-{starter-appname}_ project in the Package Explorer view
* Select *New->Class*
* Enter _org.springframework.security.samples.config_ for the *Package*
* Enter _SecurityConfig_ for the *Name*
* Click *Finish*
* Replace the file with the following contents:
[[security-config-java]]
.src/main/java/org/springframework/security/samples/config/SecurityConfig.java
[source,java]
----
package org.springframework.security.samples.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.*;
@EnableWebSecurity
public class SecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
----
NOTE: The name of the configureGlobal method is not important. However, it is important to only configure AuthenticationManagerBuilder in a class annotated with either `@EnableWebSecurity`, `@EnableGlobalMethodSecurity`, or `@EnableGlobalAuthentication`. Doing otherwise has unpredictable results.
[[servlet-api-integration]]
The <<security-config-java,SecurityConfig>> will:
* Require authentication to every URL in your application
* Generate a login form for you
* Allow the user with the *Username* _user_ and the *Password* _password_ to authenticate with form based authentication
* Allow the user to logout
* 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()]

View File

@ -1,89 +0,0 @@
== Securing the application
Before securing your application, it is important to ensure that the existing application works as we did in <<running-the-{starter-appname}-application>>. Now that the application runs without security, we are ready to add security to our application. This section demonstrates the minimal steps to add Spring Security to our application.
=== Updating your dependencies
include::../{include-maven-repository}[]
In order to use Spring Security you must add the necessary dependencies. For the sample we will add the following Spring Security dependencies:
.pom.xml
[source,xml]
[subs="verbatim,attributes"]
----
<dependencies>
<!-- ... other dependency elements ... -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>{spring-security-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>{spring-security-version}</version>
</dependency>
</dependencies>
----
After you have completed this, you need to ensure that STS knows about the updated dependencies by:
* Right click on the _spring-security-samples-{starter-config-type}-{starter-appname}_ application
* Select *Maven->Update project...*
* Ensure the project is selected, and click *OK*
=== Creating your Spring Security configuration
The next step is to create a Spring Security configuration.
* In the Package Explorer view, right click on the folder _src/main/webapp_
* Select *New->Folder*
* Enter _WEB-INF/spring_ for the *Folder name*
* Then right click on the new folder _WEB-INF/spring_
* Select *New->File*
* Enter _security.xml_ for the *File name*
* Click *Finish*
* Replace the contents of the file with the following:
[[security-config-xml]]
.src/main/webapp/WEB-INF/spring/security.xml
[source,xml]
----
<b:beans xmlns="http://www.springframework.org/schema/security"
xmlns:b="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security https://www.springframework.org/schema/security/spring-security.xsd">
<http />
<user-service>
<user name="user" password="password" authorities="ROLE_USER" />
</user-service>
</b:beans>
----
[[servlet-api-integration]]
The <<security-config-xml,security-config-xml>> will:
* Require authentication to every URL in your application
* Generate a login form for you
* Allow the user with the *Username* _user_ and the *Password* _password_ to authenticate with form based authentication
* Allow the user to logout
* 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()]

View File

@ -1,14 +0,0 @@
In order to resolve Spring Security milestones and release candidates add the Spring Milestone repository. For our example, the repository has already been added for you. In the event you were working on another application, you would need to ensure you add the following to your pom:
.pom.xml
[source,xml]
----
<repositories>
<!-- ... possibly other repository elements ... -->
<repository>
<id>spring-milestone</id>
<name>Spring Milestone Repository</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
----

View File

@ -1 +0,0 @@
Spring Security GA releases are included within Maven Central, so no additional Maven repositories are necessary.

View File

@ -1,14 +0,0 @@
In order to resolve Spring Security SNAPSHOT dependencies add the Spring Snapshot repository. For our example, the repository has already been added for you. In the event you were working on another application, you would need to ensure you add the following to your pom:
.pom.xml
[source,xml]
----
<repositories>
<!-- ... possibly other repository elements ... -->
<repository>
<id>spring-snapshot</id>
<name>Spring Snapshot Repository</name>
<url>https://repo.spring.io/snapshot</url>
</repository>
</repositories>
----

View File

@ -1,46 +0,0 @@
////
Variables:
starter-appname: the name of the module users should start with to complete the exercise
starter-config-type: the type of configuration the starter sample uses: javaconfig, xml, boot
completed-appname: the name of the module that contains the completed application
completed-config-type: the type of configuration the completed sample uses: javaconfig, xml, boot
download-url: the URL to download the Spring Security distribution
////
== Setting up the sample
This section outlines how to setup a workspace within https://spring.io/tools[Eclipse IDE with Spring Tools] so that you can follow along with this guide. The next section outlines generic steps for how to apply Spring Security to your existing application. While you could simply apply the steps to your existing application, we encourage you to follow along with this guide in order to reduce the complexity.
=== Obtaining the sample project
Clone the {gh-samples-url}[Spring Security Samples project] to a known location and remember it as _SPRING_SECURITY_HOME_.
[NOTE]
====
These samples are being migrated to a separate project, however, you can still find
the not migrated samples in an older branch of the {gh-old-samples-url}[Spring Security repository].
====
=== Import the {starter-appname} sample application
In order to follow along, we encourage you to import the {starter-appname} sample application into your IDE. You may use any IDE you prefer, but the instructions in this guide will assume you are using Spring Tool Suite (STS).
TIP: The completed sample application can be found at _SPRING_SECURITY_HOME_/samples/{completed-config-type}/{completed-appname}
* If you do not have STS installed, download STS from https://spring.io/tools
* Start STS and import the sample application into STS using the following steps:
** *File->Import*
** *Existing Maven Projects*
** Click *Next >*
** Click *Browse...*
** Navigate to the samples (i.e. _SPRING_SECURITY_HOME_/samples/{starter-config-type}/{starter-appname}) and click *OK*
** Click *Finish*
=== Running the {starter-appname} application
In the following exercise we will be modifying the _spring-security-samples-{starter-config-type}-{starter-appname}_ application. Before we make any changes, it is best to verify that the sample works properly. Perform the following steps to ensure that _spring-security-samples-{starter-config-type}-{starter-appname}_ works.
* Right click on the _spring-security-samples-{starter-config-type}-{starter-appname}_ application
* Select *Run As->Spring Boot App*

View File

@ -1,48 +0,0 @@
////
Variables:
starter-appname: the name of the module users should start with to complete the exercise
starter-config-type: the type of configuration the starter sample uses: javaconfig, xml, boot
completed-appname: the name of the module that contains the completed application
completed-config-type: the type of configuration the completed sample uses: javaconfig, xml, boot
download-url: the URL to download the Spring Security distribution
////
== Setting up the sample
This section outlines how to setup a workspace within https://spring.io/tools[Eclipse IDE with Spring Tools] so that you can follow along with this guide. The next section outlines generic steps for how to apply Spring Security to your existing application. While you could simply apply the steps to your existing application, we encourage you to follow along with this guide in order to reduce the complexity.
=== Obtaining the sample project
Clone the {gh-samples-url}[Spring Security Samples project] to a known location and remember it as _SPRING_SECURITY_HOME_.
[NOTE]
====
These samples are being migrated to a separate project, however, you can still find
the not migrated samples in an older branch of the {gh-old-samples-url}[Spring Security repository].
====
=== Import the {starter-appname} sample application
In order to follow along, we encourage you to import the {starter-appname} sample application into your IDE. You may use any IDE you prefer, but the instructions in this guide will assume you are using Spring Tool Suite (STS).
TIP: The completed sample application can be found at _SPRING_SECURITY_HOME_/samples/{completed-config-type}/{completed-appname}
* If you do not have STS installed, download STS from https://spring.io/tools
* Start STS and import the sample application into STS using the following steps:
** *File->Import*
** *Existing Maven Projects*
** Click *Next >*
** Click *Browse...*
** Navigate to the samples (i.e. _SPRING_SECURITY_HOME_/samples/{starter-config-type}/{starter-appname}) and click *OK*
** Click *Finish*
=== Running the {starter-appname} application
In the following exercise we will be modifying the _spring-security-samples-{starter-config-type}-{starter-appname}_ application. Before we make any changes, it is best to verify that the sample works properly. Perform the following steps to ensure that _spring-security-samples-{starter-config-type}-{starter-appname}_ works.
* Right click on the _spring-security-samples-{starter-config-type}-{starter-appname}_ application
* Select *Run As->Run on Server*
* Select the latest tc Server
* Click *Finish*

View File

@ -1,249 +0,0 @@
= Creating a Custom Login Form
:author: Rob Winch
:starter-appname: hellomvc
:starter-config-type: javaconfig
:completed-appname: form
:completed-config-type: javaconfig
:include-dir: _includes
This guide builds off of link:hellomvc-javaconfig.html[Hello Spring MVC Security Java Config] to explain how to configure and use a custom login form with Spring Security Java Configuration.
include::{include-dir}/setting-up-the-sample.asc[]
Verify the application is working:
* A page displaying a user's inbox can be seen at http://localhost:8080/sample/ after authenticating with the *username* _user_ and the *password* _password_.
* Try clicking on the Compose link and creating a message. The message details should be displayed.
* Now click on the Inbox link and see the message listed. You can click on the summary link to see the details displayed again.
= Overriding the default configure(HttpSecurity) method
As we saw in link:hellomvc-javaconfig.html[Hello Spring MVC Security Java Config], Spring Security's `WebSecurityConfigurerAdapter` provides some convenient defaults to get our application
up and running quickly. However, our login form does not look like the rest of our application. Let's see how we can update our configuration to use a custom form.
== Default configure(HttpSecurity)
The default configuration for the configure(HttpSecurity) method can be seen below:
[source,java]
----
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated() <1>
.and()
.formLogin() <2>
.and()
.httpBasic(); <3>
}
----
The configuration ensures that:
<1> every request requires the user to be authenticated
<2> form based authentication is supported
<3> HTTP Basic Authentication is supported
== Configuring a custom login page
We will want to ensure we compensate for overriding these defaults in our updates. Open up the `SecurityConfig` and insert the configure method as shown below:
.src/main/java/org/springframework/security/samples/config/SecurityConfig.java
[source,java]
----
// ...
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login");
}
// ...
}
----
The line `loginPage("/login")` instructs Spring Security
* when authentication is required, redirect the browser to */login*
* we are in charge of rendering the login page when */login* is requested
* when authentication attempt fails, redirect the browser to */login?error* (since we have not specified otherwise)
* we are in charge of rendering a failure page when */login?error* is requested
* when we successfully logout, redirect the browser to */login?logout* (since we have not specified otherwise)
* we are in charge of rendering a logout confirmation page when */login?logout* is requested
Go ahead and start up the server and try visiting http://localhost:8080/sample/ to see the updates to our configuration. In many browsers you will see an error similar to *This webpage has a redirect loop*. What is happening?
== Granting access to unauthenticated users
The issue is that Spring Security is protecting access to our custom login page. In particular the following is happening:
* We make a request to our web application
* Spring Security sees that we are not authenticated
* We are redirected to */login*
* The browser requests */login*
* Spring Security sees that we are not authenticated
* We are redirected to */login* ...
To fix this we need to instruct Spring Security to allow anyone to access the */login* URL. We can easily do this with the following updates:
.src/main/java/org/springframework/security/samples/config/SecurityConfig.java
[source,java]
----
// ...
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
// ...
}
----
The method `formLogin().permitAll()` statement instructs Spring Security to allow any access to any URL (i.e. */login* and */login?error*) associated to `formLogin()`.
NOTE: Granting access to the `formLogin()` URLs is not done by default since Spring Security needs to make certain assumptions about what is allowed and what is not. To be secure, it is best to ensure granting access to resources is explicit.
Start up the server and try visiting http://localhost:8080/sample/ to see the updates to our configuration. You should now get a 500 error stating **Error resolving template "login"**.
= Creating a login page
Within Spring Web MVC there are two steps to creating our login page:
* Creating a controller
* Creating a view
== Configuring a login view controller
Within Spring Web MVC, the first step is to ensure that we have a controller that can point to our view. Since our project adds the *javaconfig/messages* project as a dependency and it contains a view controller for */login* we do not need to create a controller within our application. For reference, you can see the configuration below:
[source,java]
----
// ...
@EnableWebMvc
@ComponentScan("org.springframework.security.samples.mvc")
public class WebMvcConfiguration implements WebMvcConfigurer {
// ...
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
----
== Creating a login view
Our existing configuration means that all we need to do is create a *login.html* file with the following contents:
.src/main/resources/views/login.html
[source,xml]
----
<html xmlns:th="https://www.thymeleaf.org">
<head th:include="layout :: head(title=~{::title},links=~{})">
<title>Please Login</title>
</head>
<body th:include="layout :: body" th:with="content=~{::content}">
<div th:fragment="content">
<form name="f" th:action="@{/login}" method="post"> <1>
<fieldset>
<legend>Please Login</legend>
<div th:if="${param.error}" class="alert alert-error"> <2>
Invalid username and password.
</div>
<div th:if="${param.logout}" class="alert alert-success"> <3>
You have been logged out.
</div>
<label for="username">Username</label>
<input type="text" id="username" name="username"/> <4>
<label for="password">Password</label>
<input type="password" id="password" name="password"/> <5>
<div class="form-actions">
<button type="submit" class="btn">Log in</button>
</div>
</fieldset>
</form>
</div>
</body>
</html>
----
<1> The URL we submit our username and password to is the same URL as our login form (i.e. */login*), but a *POST* instead of a *GET*.
<2> When authentication fails, the browser is redirected to */login?error* so we can display an error message by detecting if the parameter *error* is non-null.
<3> When we are successfully logged out, the browser is redirected to */login?logout* so we can display an logout success message by detecting if the parameter *logout* is non-null.
<4> The username should be present on the HTTP parameter username
<5> The password should be present on the HTTP parameter password
IMPORTANT: Do not display details about why authentication failed. For example, we do not want to display that the user does not exist as this will tell an attacker that they should try a different username.
TIP: We use Thymeleaf to automatically add the CSRF token to our form. If we were not using Thymeleaf or Spring MVCs taglib we could also manually add the CSRF token using `<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>`.
Start up the server and try visiting http://localhost:8080/sample/ to see the updates to our configuration. We now see our login page, but it does not look very pretty. The issue is that we have not granted access to the css files.
== Grant access to remaining resources
We need to update our configuration to allow anyone to access our resources and our logout pages. Update the configuration as shown below:
.src/main/java/org/springframework/security/samples/config/SecurityConfig.java
[source,java]
----
// ...
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll() <1>
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout() <2>
.permitAll();
}
// ...
}
----
<1> This allows anyone to access a URL that begins with */resources/*. Since this is where our css, javascript, and images are stored all our static resources are viewable by anyone.
<2> As you might expect, `logout().permitAll()` allows any user to request logout and view logout success URL.
Restart the server and try visiting http://localhost:8080/sample/ to see the updates to our configuration. We now see a custom login page that looks like the rest of our application.
* Try entering an invalid username and password. You will see our error message is displayed.
* Try entering a valid username (user) and password (password). You will be authenticated successfully.
* Try clicking the Log Out button. You will see our logout success message
== Conclusion
You should now know how to add a custom login form using Spring Security's Java Configuration. To learn more refer to the link:index.html[Spring Security Guides index page].

View File

@ -1,127 +0,0 @@
= Hello Spring MVC Security Java Config
:author: Rob Winch
:starter-appname: insecuremvc
:starter-config-type: xml
:completed-appname: hellomvc
:completed-config-type: javaconfig
:include-dir: _includes
:hello-include-dir: _hello-includes
This guide provides instructions on how to add Spring Security to an existing Spring MVC application without the use of XML.
include::{include-dir}/setting-up-the-sample.asc[]
Verify the application is working:
* A page displaying a user's inbox can be seen at http://localhost:8080/sample/
* Try clicking on the Compose link and creating a message. The message details should be displayed.
* Now click on the Inbox link and see the message listed. You can click on the summary link to see the details displayed again.
include::{hello-include-dir}/secure-the-application-javaconfig.asc[]
=== Registering Spring Security with the war
We have created the Spring Security configuration, but we still need to register it with the war. This can be done using the following steps:
* Right click the _spring-security-samples-{starter-config-type}-{starter-appname}_ project the Package Explorer view
* Select *New->Class*
* Enter _org.springframework.security.samples.config_ for the *Package*
* Enter MessageSecurityWebApplicationInitializer for the *Name*
* Click *Finish*
* Replace the file with the following contents:
.src/main/java/org/springframework/security/samples/config/MessageSecurityWebApplicationInitializer.java
[source,java]
----
package org.springframework.security.samples.config;
import org.springframework.security.web.context.*;
public class MessageSecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
}
----
The `MessageSecurityWebApplicationInitializer` will automatically register the springSecurityFilterChain Filter for every URL in your application. If Filters are added within other `WebApplicationInitializer` instances we can use `@Order` to control the ordering of the Filter instances.
=== Verify SecurityConfig is loaded
Just because <<security-config-java,SecurityConfig>> exists, does not mean that our Spring application knows about it. In this instance, our Spring root application context is initialized using MessageWebApplicationInitializer which is included with our spring-security-samples-javaconfig-messages project. You can find a snippet of it below:
[[message-web-application-inititializer-java]]
.MessageWebApplicationInitializer.java
[source,java]
----
public class MessageWebApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfiguration.class };
}
// ... other overrides ...
}
----
You will notice it is loading the `RootConfiguration` class which is also included in our spring-security-samples-javaconfig-messages project.
[[root-configuration-java]]
.RootConfiguration.java
[source,java]
----
@Configuration
@ComponentScan
public class RootConfiguration {
}
----
The `@ComponentScan` is loading all configuration within the same package (and child packages) as `RootConfiguration`. Since <<security-config-java,SecurityConfig>> is in this package, it will be loaded with our existing setup and there is nothing more to do.
NOTE: Had <<security-config-java,SecurityConfig>> not been loaded, we could have used an `@Import(SecurityConfig.class)` above the class definition of <<root-configuration-java,RootConfiguration>> or added <<security-config-java,SecurityConfig>> as one of the results for `getRootConfigClasses()`.
include::{hello-include-dir}/exploring-the-secured-application-javaconfig.asc[]
==== Displaying the user name
Now that we have authenticated, let's see how our application is displaying the username if the user is authenticated.
.messages/src/main/resources/views/layout.html
[source,html]
----
<div th:if="${#httpServletRequest.remoteUser != null}">
<p th:text="${#httpServletRequest.remoteUser}">
sample_user
</p>
</div>
----
In our samples we use https://www.thymeleaf.org/[Thymeleaf], but any view technology will work. Any technology can inspect the `HttpServletRequest#getRemoteUser()` to view the current user since Spring Security integrates with the <<servlet-api-integration,Servlet API methods>>.
WARNING: The Thymeleaf ensures the username is escaped to avoid https://en.wikipedia.org/wiki/Cross-site_scripting[XSS vulnerabilities] Regardless of how an application renders user inputed values, it should ensure that the values are properly escaped.
==== Logging out
We can view the user name, but how are we able to log out? Below you can see how we are able to log out.
.messages/src/main/resources/views/layout.html
[source,html]
----
<form th:action="@{/logout}" method="post">
<input type="submit" value="Log out" />
</form>
----
In order to help protect against https://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attacks], by default, Spring Security Java Configuration log out requires:
* the HTTP method must be a POST
* the CSRF token must be added to the request. Since we have used `@EnableWebSecurity` and are using Thymeleaf, the CSRF token is automatically added as a hidden input for you (view the source to see it).
NOTE: If you were not using Spring MVC taglibs or Thymeleaf, you can access the CsrfToken on the ServletRequest using the attribute _csrf. You can find an example of including the CSRF token in a JSP within the link:helloworld-javaconfig.html[Hello Spring Security Java Config].
Restart the application server and click the Log out button and see that the application logs you out successfully.
== Conclusion
You should now know how to secure your application using Spring Security without using any XML. Next, we will see how to link:form-javaconfig.html[customize our login form].

View File

@ -1,97 +0,0 @@
= Hello Spring Security with Boot
:author: Joe Grandja
:starter-appname: insecure
:starter-config-type: boot
:completed-appname: helloworld
:completed-config-type: boot
:include-dir: _includes
:hello-include-dir: _hello-includes
This guide provides instructions on how to add Spring Security to an existing Spring Boot application.
include::{include-dir}/setting-up-the-sample-boot.asc[]
Verify the application is working by navigating to http://localhost:8080/
Click on the *_secured pages_* link and verify the page states *TODO Secure this*
Once you have verified the application runs, stop the application server using the following steps:
* In the _Boot Dashboard_ view select the running application
* Click the stop button (a red square) to stop the application
include::{hello-include-dir}/secure-the-application-boot.asc[]
include::{hello-include-dir}/exploring-the-secured-application-boot.asc[]
==== Displaying the user name
Now that we have authenticated, let's update the application to display the username. Update the complete content of */index.html* with the following:
.src/main/resources/templates/index.html
[source,html]
----
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<title>Hello Spring Security</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
</head>
<body>
<div th:fragment="logout" class="logout" sec:authorize="isAuthenticated()"> <1>
Logged in user: <span sec:authentication="name"></span> | <2>
Roles: <span sec:authentication="principal.authorities"></span> <3>
<div>
<form action="#" th:action="@{/logout}" method="post"> <4>
<input type="submit" value="Logout" />
</form>
</div>
</div>
<h1>Hello Spring Security</h1>
<p>This is an unsecured page, but you can access the secured pages after authenticating.</p>
<ul>
<li>Go to the <a href="/user/index" th:href="@{/user/index}">secured pages</a></li>
</ul>
</body>
</html>
----
NOTE: We are using https://www.thymeleaf.org/[Thymeleaf] for our view template engine and
https://github.com/thymeleaf/thymeleaf-extras-springsecurity[Thymeleaf - Spring Security integration modules]
in order to utilize the _sec:authentication_ and _sec:authorize_ attributes.
<1> Displays the Thymeleaf fragment (DOM Node) if the current user has been authenticated.
<2> Displays the name of the currently authenticated principal.
<3> Displays the authorities of the currently authenticated principal.
<4> The logout form.
TIP: Thymeleaf will automatically add the CSRF token to our logout form. If we were not using Thymeleaf or Spring MVCs taglib we could also manually add the CSRF token using `<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>`.
==== Update the _secured_ page
The last step is to update the _secured_ page to also display the currently authenticated principal. Update the complete content of */user/index.html* with the following:
.src/main/resources/templates/user/index.html
[source,html]
----
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
<title>Hello Spring Security</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
</head>
<body>
<div th:substituteby="index::logout"></div>
<h1>This is a secured page!</h1>
<p><a href="/index" th:href="@{/index}">Back to home page</a></p>
</body>
</html>
----
Start up the server and try visiting http://localhost:8080/ to see the updates to our application.
== Conclusion
You should now know how to secure your application using Spring Security with an existing Spring Boot application . To learn more refer to the link:index.html[Spring Security Guides index page].

View File

@ -1,113 +0,0 @@
= Hello Spring Security Java Config
:author: Rob Winch
:starter-appname: insecure
:starter-config-type: xml
:completed-appname: helloworld
:completed-config-type: javaconfig
:include-dir: _includes
:hello-include-dir: _hello-includes
This guide provides instructions on how to add Spring Security to an existing application without the use of XML.
include::{include-dir}/setting-up-the-sample.asc[]
Verify the application is working by ensuring a page stating *TODO Secure this* is displayed at http://localhost:8080/sample/
Once you have verified the application runs, stop the application server using the following steps:
* In the Servers view select the latest tc Server
* Click the stop button (a red square) to stop the application server
include::{hello-include-dir}/secure-the-application-javaconfig.asc[]
=== Registering Spring Security with the war
We have created the Spring Security configuration, but we still need to register it with the war. This can be done using the following steps:
* Navigate to the *Package Explorer* view
* Right click the *org.springframework.security.samples.config* package within the *spring-security-samples-{starter-config-type}-{starter-appname}* project
* Select *New->Class*
* Enter _SecurityWebApplicationInitializer_ for the *Name*
* Click *Finish*
* Replace the file with the following contents:
.src/main/java/org/springframework/security/samples/config/SecurityWebApplicationInitializer.java
[source,java]
----
package org.springframework.security.samples.config;
import org.springframework.security.web.context.*;
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityConfig.class);
}
}
----
The `SecurityWebApplicationInitializer` will do the following things:
* Automatically register the springSecurityFilterChain Filter for every URL in your application
* Add a ContextLoaderListener that loads the <<security-config-java,SecurityConfig>>.
NOTE: Since we were not already using Spring, this is a simple way to add our <<security-config-java,SecurityConfig>>. If we were already using Spring, then we should add our <<security-config-java,SecurityConfig>> with the reset of our Spring configuration (i.e. a subclass of AbstractContextLoaderInitializer or AbstractDispatcherServletInitializer) and use the default constructor instead.
include::{hello-include-dir}/exploring-the-secured-application-javaconfig.asc[]
==== Displaying the user name
Now that we have authenticated, let's update the application to display the username. Update the body of index.jsp to be the following:
.src/main/webapp/index.jsp
[source,html]
----
<body>
<div class="container">
<h1>This is secured!</h1>
<p>
Hello <b><c:out value="${pageContext.request.remoteUser}"/></b>
</p>
</div>
</body>
----
WARNING: The `<c:out />` tag ensures the username is escaped to avoid https://en.wikipedia.org/wiki/Cross-site_scripting[XSS vulnerabilities] Regardless of how an application renders user inputed values, it should ensure that the values are properly escaped.
Refresh the page at http://localhost:8080/sample/ and you will see the user name displayed. This works because Spring Security integrates with the <<servlet-api-integration,Servlet API methods>>
==== Logging out
Now that we can view the user name, let's update the application to allow logging out. Update the body of index.jsp to contain a log out form as shown below:
.src/main/webapp/index.jsp
[source,html]
----
<body>
<div class="container">
<h1>This is secured!</h1>
<p>
Hello <b><c:out value="${pageContext.request.remoteUser}"/></b>
</p>
<c:url var="logoutUrl" value="/logout"/>
<form class="form-inline" action="${logoutUrl}" method="post">
<input type="submit" value="Log out" />
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</div>
</body>
----
In order to help protect against https://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attacks], by default, Spring Security Java Configuration log out requires:
* the HTTP method must be a POST
* the CSRF token must be added to the request. You can access it on the ServletRequest using the attribute _csrf as illustrated above.
NOTE: If you were using Spring MVC's tag library or Thymeleaf, the CSRF token is automatically added as a hidden input for you.
Refresh the page at http://localhost:8080/sample/ and you will see the log out button. Click the logout button and see that the application logs you out successfully.
== Conclusion
You should now know how to secure your application using Spring Security without using any XML. To learn more refer to the link:index.html[Spring Security Guides index page].

View File

@ -1,136 +0,0 @@
= Hello Spring Security Xml Config
:author: Joe Grandja
:starter-appname: insecure
:starter-config-type: xml
:completed-appname: helloworld
:completed-config-type: xml
:include-dir: _includes
:hello-include-dir: _hello-includes
This guide provides instructions on how to add Spring Security to an existing application using XML configuration.
include::{include-dir}/setting-up-the-sample.asc[]
Verify the application is working by ensuring a page stating *TODO Secure this* is displayed at http://localhost:8080/sample/
Once you have verified the application runs, stop the application server using the following steps:
* In the Servers view select the latest tc Server
* Click the stop button (a red square) to stop the application server
include::{hello-include-dir}/secure-the-application-xml.asc[]
=== Registering Spring Security with the war
We have created the Spring Security configuration, but we still need to register it with the war. This can be done using the following steps:
* In the Package Explorer view, right click on the folder _src/main/webapp/WEB-INF_
* Select *New->File*
* Enter _web.xml_ for the *File name*
* Click *Finish*
* Replace the contents of the file with the following:
.src/main/webapp/WEB-INF/web.xml
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!--
- Location of the XML file that defines the root application context
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/*.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--
- Loads the root application context of this web app at startup.
- The application context is then available via
- WebApplicationContextUtils.getWebApplicationContext(servletContext).
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
----
The _web.xml_ will do the following things:
* Registers the `springSecurityFilterChain` Filter for every URL in your application
* Adds a `ContextLoaderListener` that loads the <<security-config-xml,security-config-xml>>.
include::{hello-include-dir}/exploring-the-secured-application-xml.asc[]
==== Displaying the user name
Now that we have authenticated, let's update the application to display the username. Update the body of index.jsp to be the following:
.src/main/webapp/index.jsp
[source,html]
----
<body>
<div class="container">
<h1>This is secured!</h1>
<p>
Hello <b><c:out value="${pageContext.request.remoteUser}"/></b>
</p>
</div>
</body>
----
WARNING: The `<c:out />` tag ensures the username is escaped to avoid https://en.wikipedia.org/wiki/Cross-site_scripting[XSS vulnerabilities] Regardless of how an application renders user inputed values, it should ensure that the values are properly escaped.
Refresh the page at http://localhost:8080/sample/ and you will see the user name displayed. This works because Spring Security integrates with the <<servlet-api-integration,Servlet API methods>>
==== Logging out
Now that we can view the user name, let's update the application to allow logging out. Update the body of index.jsp to contain a log out form as shown below:
.src/main/webapp/index.jsp
[source,html]
----
<body>
<div class="container">
<h1>This is secured!</h1>
<p>
Hello <b><c:out value="${pageContext.request.remoteUser}"/></b>
</p>
<c:url var="logoutUrl" value="/logout"/>
<form class="form-inline" action="${logoutUrl}" method="post">
<input type="submit" value="Log out" />
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</div>
</body>
----
In order to help protect against https://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attacks], by default, Spring Security Xml Configuration log out requires:
* the HTTP method must be a POST
* the CSRF token must be added to the request. You can access it on the ServletRequest using the attribute _csrf as illustrated above.
NOTE: If you were using Spring MVC's tag library or Thymeleaf, the CSRF token is automatically added as a hidden input for you.
Refresh the page at http://localhost:8080/sample/ and you will see the log out button. Click the logout button and see that the application logs you out successfully.
== Conclusion
You should now know how to secure your application using Spring Security with XML. To learn more refer to the link:index.html[Spring Security Guides index page].

View File

@ -1,17 +0,0 @@
= Spring Security Guides
Rob Winch, Joe Grandja
These are step by step guides on how to use Spring Security.
== Hello World
These are the most basic starting points for using a web based application.
* link:helloworld-javaconfig.html[Hello Spring Security Java Config] - demonstrates how to integrate Spring Security with an existing application using Java-based configuration
* link:helloworld-boot.html[Hello Spring Security with Boot] - demonstrates how to integrate Spring Security with an existing Spring Boot application
* link:helloworld-xml.html[Hello Spring Security Xml Config] - demonstrates how to integrate Spring Security with an existing application using Xml-based configuration
* link:hellomvc-javaconfig.html[Hello Spring MVC Security Java Config] - demonstrates how to integrate Spring Security with an existing Spring MVC application
== Simple Customization
* link:form-javaconfig.html[Creating a custom login form] - demonstrates how to create a custom login form

View File

@ -1,62 +0,0 @@
apply plugin: 'io.spring.convention.docs'
apply plugin: 'io.spring.convention.management-configuration'
apply plugin: 'io.spring.convention.repository'
apply plugin: 'java'
asciidoctor {
attributes([stylesheet: 'css/style.css'])
resources {
from(sourceDir) {
include "css/**"
}
}
}
asciidoctorj {
def docsTag = snapshotBuild ? 'current' : project.version
def ghTag = snapshotBuild ? 'main' : project.version
def ghUrl = "https://github.com/spring-projects/spring-security/tree/$ghTag"
def ghOldSamplesUrl = "https://github.com/spring-projects/spring-security/tree/5.4.x/samples"
def ghSamplesUrl = "https://github.com/spring-projects/spring-security-samples/tree/$samplesBranch"
def securityDocsUrl = "https://docs.spring.io/spring-security/site/docs/$docsTag"
def securityApiUrl = "$securityDocsUrl/api/"
def securityReferenceUrl = "$securityDocsUrl/reference/html5/"
def springFrameworkApiUrl = "https://docs.spring.io/spring-framework/docs/$springFrameworkVersion/javadoc-api/"
def springFrameworkReferenceUrl = "https://docs.spring.io/spring-framework/docs/$springFrameworkVersion/reference/html/"
attributes 'spring-security-version' : project.version,
'spring-boot-version' : springBootVersion,
revnumber : project.version,
'gh-url': ghUrl,
'gh-samples-url': ghSamplesUrl,
'gh-old-samples-url': ghOldSamplesUrl,
'security-api-url': securityApiUrl,
'security-reference-url': securityReferenceUrl,
'spring-framework-api-url': springFrameworkApiUrl,
'spring-framework-reference-url': springFrameworkReferenceUrl
attributeProvider resolvedVersions(project.configurations.testRuntimeClasspath)
}
docsZip {
from(project(':spring-security-docs-guides').asciidoctor) {
into 'guides'
}
}
dependencies {
management platform(project(":spring-security-dependencies"))
testImplementation "com.unboundid:unboundid-ldapsdk"
testImplementation "org.apache.directory.server:apacheds-core"
testImplementation "org.springframework:spring-core"
}
def resolvedVersions(Configuration configuration) {
return {
configuration.resolvedConfiguration
.resolvedArtifacts
.collectEntries { [(it.name + "-version"): it.moduleVersion.id.version] }
}
}
repositories {
maven { url "https://repo.spring.io/release" }
}

View File

@ -1,12 +0,0 @@
require 'asciidoctor'
require 'erb'
guard 'shell' do
watch(/^.*\.adoc$/) {|m|
Asciidoctor.render_file(m[0], :to_dir => "build/", :safe => Asciidoctor::SafeMode::UNSAFE, :attributes=> {'idprefix' => '', 'idseparator' => '-', 'copycss' => '', 'icons' => 'font', 'source-highlighter' => 'prettify', 'sectanchors' => '', 'doctype' => 'book','toc2' => '', 'spring-security-version' => '3.2.0.CI-SNAPSHOT','spring-version' => '3.2.0.RELEASE','spring4-version' => '4.0.0.RELEASE', 'revnumber' => '3.2.0.CI-SNAPSHOT', 'numbered'=>'' })
}
end
guard 'livereload' do
watch(%r{build/.+\.(css|js|html)$})
end

View File

@ -1,17 +0,0 @@
= Introduction
This section discusses the logistics of Spring Security.
include::prerequisites.adoc[leveloffset=+1]
include::community.adoc[leveloffset=+1]
include::whats-new.adoc[]
include::getting-spring-security.adoc[leveloffset=+1]
include::features.adoc[leveloffset=+1]
include::modules.adoc[leveloffset=+1]
include::samples.adoc[leveloffset=+1]

View File

@ -1,9 +0,0 @@
= Book Title
Rob Winch
[abstract]
This is the actual content.
== First Section
And off we go.

View File

@ -1,5 +0,0 @@
@import 'spring.css';
a code {
color: #097dff;
}

View File

@ -1,11 +0,0 @@
<productname>Spring Security</productname>
<releaseinfo>{spring-security-version}</releaseinfo>
<copyright>
<year>2004-2019</year>
</copyright>
<legalnotice>
<para>Copies of this document may be made for your own use and for distribution to
others, provided that you do not charge any fee for such copies and further provided
that each copy contains this Copyright Notice, whether distributed in print or
electronically.</para>
</legalnotice>

View File

@ -1,19 +0,0 @@
= Spring Security Reference
Ben Alex; Luke Taylor; Rob Winch; Gunnar Hillert; Joe Grandja; Jay Bryant; Eddú Meléndez; Josh Cummings; Dave Syer; Eleftheria Stein
:include-dir: _includes
:source-indent: 0
:tabsize: 4
:toc: left
// FIXME: Add links for authentication, authorization, common attacks
Spring Security is a framework that provides authentication, authorization, and protection against common attacks.
// FIXME: Add links for imperative and reactive applications
With first class support for both imperative and reactive applications, it is the de-facto standard for securing Spring-based applications.
include::{include-dir}/about/index.adoc[]
include::{include-dir}/servlet/index.adoc[]
include::{include-dir}/reactive/index.adoc[]

View File

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 49 KiB

View File

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

Before

Width:  |  Height:  |  Size: 68 KiB

After

Width:  |  Height:  |  Size: 68 KiB

View File

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

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