Skip to content

Commit 8421594

Browse files
jzheauxJay Bryantrwinch
committed
Replace Servlet Guides w/ Hello World Samples
Issue gh-2567 Co-authored-by: Jay Bryant <[email protected]> Co-authored-by: Rob Winch <[email protected]>
1 parent 25b5f48 commit 8421594

File tree

7 files changed

+363
-36
lines changed

7 files changed

+363
-36
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
[[servlet-hello-boot]]
2+
= Hello Spring Security (Boot)
3+
4+
This section covers the minimum setup for how to use Spring Security with Spring Boot.
5+
For how to use Spring Security with Java Configuration, see <<servlet-hello-jc>>.
6+
For how to use Spring Security with XML Configuration, see <<servlet-hello-xml>>.
7+
8+
NOTE: The completed application can be found at {gh-samples-url}/boot/helloworld[samples/boot/helloworld]
9+
10+
[[servlet-hello-boot-dependencies]]
11+
== Updating Dependencies
12+
13+
The only step you need to do is update the dependencies by using <<getting-maven-boot,Maven>> or <<getting-gradle-boot,Gradle>>.
14+
For your convenience, you can download a minimal Spring Boot + Spring Security application by https://start.spring.io/starter.zip?type=maven-project&language=java&bootVersion=2.1.2.RELEASE&baseDir=hello-spring-security&groupId=sample&artifactId=sample&name=hello-spring-security&description=Demo+project+for+Spring+Boot&packageName=sample&packaging=jar&javaVersion=1.8&autocomplete=&style=security&style=web&generate-project=[clicking here].
15+
16+
== Starting Hello Spring Security Boot
17+
18+
You can now https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-running-with-the-maven-plugin[run the Spring Boot application] by using the Maven Plugin's `run` goal.
19+
The following example shows how to do so (and the beginning of the output from doing so):
20+
21+
.Running Spring Boot Application
22+
====
23+
[source,bash]
24+
----
25+
$ ./mvn spring-boot:run
26+
...
27+
INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration :
28+
29+
Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336
30+
31+
...
32+
----
33+
====
34+
35+
36+
[[servlet-hello-boot-auto-configuration]]
37+
== Spring Boot Auto Configuration
38+
39+
Spring Boot automatically:
40+
41+
* Enables Spring Security's default configuration, which creates a servlet `Filter` as a bean named `springSecurityFilterChain`.
42+
This bean is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, and so on) within your application.
43+
* Creates a `UserDetailsService` bean with a username of `user` and a randomly generated password that is logged to the console.
44+
* Registers the `Filter` with a bean named `springSecurityFilterChain` with the Servlet container for every request.
45+
46+
Spring Boot is not configuring much, but it does a lot.
47+
A summary of the features follows:
48+
49+
* Require an authenticated user for any interaction with the application
50+
* Generate a default login form for you
51+
* Let the user with a username of `user` and a password that is logged to the console to authenticate with form-based authentication (in the preceding example, the password is `8e557245-73e2-4286-969a-ff57fe326336`)
52+
* Protects the password storage with BCrypt
53+
* Lets the user log out
54+
* http://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attack] prevention
55+
* http://en.wikipedia.org/wiki/Session_fixation[Session Fixation] protection
56+
* Security Header integration
57+
** http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security[HTTP Strict Transport Security] for secure requests
58+
** http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx[X-Content-Type-Options] integration
59+
** Cache Control (can be overridden later by your application to allow caching of your static resources)
60+
** http://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx[X-XSS-Protection] integration
61+
** X-Frame-Options integration to help prevent http://en.wikipedia.org/wiki/Clickjacking[Clickjacking]
62+
* Integrate with the following Servlet API methods:
63+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[`HttpServletRequest#getRemoteUser()`]
64+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[`HttpServletRequest.html#getUserPrincipal()`]
65+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[`HttpServletRequest.html#isUserInRole(java.lang.String)`]
66+
** http://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)`]
67+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[`HttpServletRequest.html#logout()`]

docs/manual/src/docs/asciidoc/_includes/servlet/hello/guides.adoc

Lines changed: 0 additions & 34 deletions
This file was deleted.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
= Hello Spring Security
2+
3+
This section covers a minimal Spring Security application that uses <<servlet-hello-boot,Spring Boot>>, <<servlet-hello-jc,Java Configuration>>, or <<servlet-hello-xml,XML Configuration>>.
4+
// FIXME add Spring Boot
5+
6+
include::boot.adoc[leveloffset=+1]
7+
include::java-configuration.adoc[leveloffset=+1]
8+
include::xml-configuration.adoc[leveloffset=+1]
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
[[servlet-hello-jc]]
2+
= Hello Spring Security (Java Configuration)
3+
4+
This section covers how to use Spring Security with Java Configuration.
5+
For how to use Spring Security with XML configuration, see <<servlet-hello-xml>>.
6+
For how to use Spring Security with Spring Boot configuration, see <<servlet-hello-boot>>.
7+
8+
NOTE: You can find the completed application at {gh-samples-url}/javaconfig/helloworld[samples/javaconfig/helloworld].
9+
10+
== Updating Dependencies
11+
12+
The first step is to update the dependencies by using <<getting-maven-without-spring-boot,Maven>> or <<gradle-without-spring-boot,Gradle>>.
13+
14+
15+
[[servlet-hello-jc-ews]]
16+
== Minimal `@EnableWebSecurity` Configuration
17+
18+
The first step is to create our Spring Security Java configuration.
19+
The configuration creates a servlet `Filter` (known as the `springSecurityFilterChain`), which is responsible for all the security features (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, and so on) within your application.
20+
The following example shows the most basic example of a Spring Security Java Configuration:
21+
22+
.WebSecurity.java
23+
====
24+
[source,java]
25+
----
26+
import org.springframework.context.annotation.*;
27+
import org.springframework.security.config.annotation.web.configuration.*;
28+
import org.springframework.security.core.userdetails.*;
29+
import org.springframework.security.provisioning.*;
30+
31+
@EnableWebSecurity
32+
public class WebSecurityConfig {
33+
34+
// @formatter:off
35+
@Bean
36+
public UserDetailsService userDetailsService() {
37+
UserDetails user = User.withDefaultPasswordEncoder()
38+
.username("user")
39+
.password("password")
40+
.roles("USER")
41+
.build();
42+
return new InMemoryUserDetailsManager(user);
43+
}
44+
// @formatter:on
45+
}
46+
----
47+
====
48+
49+
There really is not much to this configuration, but it does a lot.
50+
A summary of the features follows:
51+
52+
* Require an authenticated user for any interaction with the application
53+
* Generate a default login form for you
54+
* Lets the user with a username of `user` and a password of `password` authenticate with form-based authentication
55+
* Protects the password storage with BCrypt
56+
* Lets the user log out
57+
* http://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attack] prevention
58+
* http://en.wikipedia.org/wiki/Session_fixation[Session Fixation] protection
59+
* Security Header integration
60+
** http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security[HTTP Strict Transport Security] for secure requests
61+
** http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx[X-Content-Type-Options] integration
62+
** Cache Control (can be overridden later by your application to allow caching of your static resources)
63+
** http://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx[X-XSS-Protection] integration
64+
** X-Frame-Options integration to help prevent http://en.wikipedia.org/wiki/Clickjacking[Clickjacking]
65+
* Integrate with the following Servlet API methods:
66+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[`HttpServletRequest#getRemoteUser()`]
67+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[`HttpServletRequest.html#getUserPrincipal()`]
68+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[`HttpServletRequest.html#isUserInRole(java.lang.String)`]
69+
** http://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)`]
70+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[`HttpServletRequest.html#logout()`]
71+
72+
// FIXME: After completed rewriting, link to all the sections of doc that this relates to
73+
74+
== Using `AbstractSecurityWebApplicationInitializer`
75+
76+
The next step is to register the `springSecurityFilterChain` with the war.
77+
Spring Security provides a base class (`AbstractSecurityWebApplicationInitializer`) that leverages https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-servlet[Spring's WebApplicationInitializer support].
78+
79+
The following example shows an example configuration:
80+
81+
.SecurityInitializer.java
82+
====
83+
[source,java]
84+
----
85+
import org.springframework.security.web.context.*;
86+
87+
public class SecurityInitializer
88+
extends AbstractSecurityWebApplicationInitializer {
89+
90+
public SecurityInitializer() {
91+
super(WebSecurityConfig.class);
92+
}
93+
}
94+
----
95+
====
96+
97+
The `SecurityInitializer` does the following things:
98+
99+
* Adds a `ContextLoaderListener` that loads the <<servlet-hello-ews,`WebSecurityConfig`>>.
100+
* Finds the bean of type `Filter` named `springSecurityFilterChain` and registers it to process every URL in the application.
101+
102+
103+
[NOTE]
104+
====
105+
If you are integrating with a Spring MVC application, be sure to configure the `DispatcherServlet` to load the configuration from the root `ApplicationContext`.
106+
The following example shows how to do so:
107+
108+
.MvcInitializer.java
109+
=====
110+
[source,java]
111+
----
112+
public class MvcInitializer extends
113+
AbstractAnnotationConfigDispatcherServletInitializer {
114+
115+
// the Root Config is registered in SecurityInitializer
116+
@Override
117+
protected Class<?>[] getRootConfigClasses() {
118+
return null;
119+
}
120+
121+
// the Spring MVC configuration should be added to SecurityInitializer constructor
122+
// i.e.
123+
// super(MvcConfig.class, WebSecurityConfig.class);
124+
@Override
125+
protected Class<?>[] getServletConfigClasses() {
126+
return null;
127+
}
128+
129+
@Override
130+
protected String[] getServletMappings() {
131+
return new String[] { "/" };
132+
}
133+
134+
}
135+
136+
----
137+
=====
138+
====
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
[[servlet-hello-xml]]
2+
= Hello Spring Security (XML)
3+
4+
This section covers how to use Spring Security with XML Configuration.
5+
For how to use Spring Security with Java configuration, see <<servlet-hello-jc>>.
6+
For how to use Spring Security with Spring Boot configuration, see <<servlet-hello-boot>>.
7+
8+
== Updating Dependencies
9+
10+
The first step is to update the dependencies by using <<maven-without-spring-boot,Maven>> or <<gradle-without-spring-boot,Gradle>>.
11+
12+
13+
[[servlet-hello-xml-http]]
14+
== Minimal `<http>` Configuration
15+
16+
In this section, we discuss how to use Spring Security with XML Configuration.
17+
18+
NOTE: The completed application can be found at {gh-samples-url}/xml/helloworld[samples/xml/helloworld]
19+
// FIXME: Link to Java Configuration and Boot
20+
21+
The first step is to create our Spring Security XML Configuration.
22+
The configuration creates a Servlet `Filter` (known as the `springSecurityFilterChain`), which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, and so on) within your application.
23+
The following example shows the most basic example of a Spring Security XML Configuration:
24+
25+
.src/main/webapp/WEB-INF/spring/security.xml
26+
====
27+
[source,xml]
28+
----
29+
<b:beans xmlns="http://www.springframework.org/schema/security"
30+
xmlns:b="http://www.springframework.org/schema/beans"
31+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
32+
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
33+
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
34+
<http />
35+
36+
<user-service>
37+
<user name="user" password="{noop}password" authorities="ROLE_USER" />
38+
</user-service>
39+
</b:beans>
40+
41+
----
42+
====
43+
44+
45+
There really is not much to this configuration, but it does a lot.
46+
A summary of the features follows:
47+
48+
* Require an authenticated user for any interaction with the application
49+
* Generate a default login form for you
50+
* Lets the user with a username of `user` and a password of `password` authenticate with form-based authentication
51+
* Protects the password storage with BCrypt
52+
* Lets the user to log out
53+
* http://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attack] prevention
54+
* http://en.wikipedia.org/wiki/Session_fixation[Session Fixation] protection
55+
* Security Header integration
56+
** http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security[HTTP Strict Transport Security] for secure requests
57+
** http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx[X-Content-Type-Options] integration
58+
** Cache Control (can be overridden later by your application to allow caching of your static resources)
59+
** http://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx[X-XSS-Protection] integration
60+
** X-Frame-Options integration to help prevent http://en.wikipedia.org/wiki/Clickjacking[Clickjacking]
61+
* Integrate with the following Servlet API methods:
62+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[`HttpServletRequest#getRemoteUser()`]
63+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[`HttpServletRequest.html#getUserPrincipal()`]
64+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[`HttpServletRequest.html#isUserInRole(java.lang.String)`]
65+
** http://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)`]
66+
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[`HttpServletRequest.html#logout()`]
67+
68+
// FIXME: After completed rewriting, link to all the sections of doc that this relates to
69+
70+
71+
[[servlet-hello-xml-webxml]]
72+
== `web.xml` Configuration
73+
74+
The next step is to ensure that our Security configuration is being read in.
75+
To do so, we need to ensure a `ContextLoaderListener` is registered and the `contextConfigLocation` is including the configuration.
76+
The following example shows how to do so:
77+
78+
.src/main/webapp/WEB-INF/web.xml
79+
====
80+
[source,xml]
81+
----
82+
<?xml version="1.0" encoding="UTF-8"?>
83+
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
84+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
85+
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
86+
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
87+
88+
<!--
89+
Loads the Spring configurations from contextConfigLocation
90+
-->
91+
<listener>
92+
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
93+
</listener>
94+
95+
<!--
96+
The locations of the Spring Configuration. In this case, all configuration is
97+
in /WEB-INF/spring/
98+
-->
99+
<context-param>
100+
<param-name>contextConfigLocation</param-name>
101+
<param-value>
102+
/WEB-INF/spring/*.xml
103+
</param-value>
104+
</context-param>
105+
106+
<!--
107+
DelegatingFilterProxy looks for a Spring bean by the name of filter (springSecurityFilterChain) and delegates
108+
all work to that Bean. This is how the Servlet Container can a Spring Bean to act as a Servlet Filter.
109+
-->
110+
<filter>
111+
<filter-name>springSecurityFilterChain</filter-name>
112+
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
113+
</filter>
114+
<filter-mapping>
115+
<filter-name>springSecurityFilterChain</filter-name>
116+
<url-pattern>/*</url-pattern>
117+
</filter-mapping>
118+
119+
</web-app>
120+
----
121+
====
122+
123+
[NOTE]
124+
====
125+
If you integrate with an existing Spring MVC application, be sure to configure the `DispatcherServlet` to load the configuration from the root `ApplicationContext`.
126+
The following example shows how to do so:
127+
128+
=====
129+
.src/main/webapp/WEB-INF/web.xml
130+
[source,xml]
131+
----
132+
<servlet>
133+
<servlet-name>spring</servlet-name>
134+
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
135+
<!-- Load Spring MVC configuration from root ApplicationContext (context-param from above) -->
136+
<init-param>
137+
<param-name>contextConfigLocation</param-name>
138+
<param-value></param-value>
139+
</init-param>
140+
</servlet>
141+
142+
<servlet-mapping>
143+
<servlet-name>spring</servlet-name>
144+
<url-pattern>/</url-pattern>
145+
</servlet-mapping>
146+
----
147+
=====
148+
====

0 commit comments

Comments
 (0)