<commit_before>
[[jc]]
= Java Configuration

General support for https://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java[Java Configuration] was added to Spring Framework in Spring 3.1.
Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML.

If you are familiar with the <<ns-config>> then you should find quite a few similarities between it and the Security Java Configuration support.

NOTE: Spring Security provides https://github.com/spring-projects/spring-security/tree/master/samples/javaconfig[lots of sample applications] which demonstrate the use of Spring Security Java Configuration.

== Hello Web Security Java Configuration

The first step is to create our Spring Security Java Configuration.
The configuration creates a Servlet Filter known as the `springSecurityFilterChain` which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application.
You can find the most basic example of a Spring Security Java Configuration below:

[[jc-hello-wsca]]
[source,java]
----
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;

@EnableWebSecurity
public class WebSecurityConfig {

	@Bean
	public UserDetailsService userDetailsService() {
		InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
		manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
		return manager;
	}
}
----

There really isn't much to this configuration, but it does a lot.
You can find a summary of the features below:

* Require authentication to every URL in your application
* Generate a login form for you
* Allow the user with the *Username* _user_ and the *Password* _password_ to authenticate with form based authentication
* Allow the user to logout
* 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#getUserPrincipal()]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[HttpServletRequest#isUserInRole(java.lang.String)]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)[HttpServletRequest#login(java.lang.String, java.lang.String)]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[HttpServletRequest#logout()]

=== AbstractSecurityWebApplicationInitializer

The next step is to register the `springSecurityFilterChain` with the war.
This can be done in Java Configuration with https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config[Spring's WebApplicationInitializer support] in a Servlet 3.0+ environment.
Not suprisingly, Spring Security provides a base class `AbstractSecurityWebApplicationInitializer` that will ensure the `springSecurityFilterChain` gets registered for you.
The way in which we use `AbstractSecurityWebApplicationInitializer` differs depending on if we are already using Spring or if Spring Security is the only Spring component in our application.

* <<abstractsecuritywebapplicationinitializer-without-existing-spring>> - Use these instructions if you are not using Spring already
* <<abstractsecuritywebapplicationinitializer-with-spring-mvc>> - Use these instructions if you are already using Spring

=== AbstractSecurityWebApplicationInitializer without Existing Spring

If you are not using Spring or Spring MVC, you will need to pass in the `WebSecurityConfig` into the superclass to ensure the configuration is picked up.
You can find an example below:

[source,java]
----
import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
	extends AbstractSecurityWebApplicationInitializer {

	public SecurityWebApplicationInitializer() {
		super(WebSecurityConfig.class);
	}
}
----

The `SecurityWebApplicationInitializer` will do the following things:

* Automatically register the springSecurityFilterChain Filter for every URL in your application
* Add a ContextLoaderListener that loads the <<jc-hello-wsca,WebSecurityConfig>>.

=== AbstractSecurityWebApplicationInitializer with Spring MVC

If we were using Spring elsewhere in our application we probably already had a `WebApplicationInitializer` that is loading our Spring Configuration.
If we use the previous configuration we would get an error.
Instead, we should register Spring Security with the existing `ApplicationContext`.
For example, if we were using Spring MVC our `SecurityWebApplicationInitializer` would look something like the following:

[source,java]
----
import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
	extends AbstractSecurityWebApplicationInitializer {

}
----

This would simply only register the springSecurityFilterChain Filter for every URL in your application.
After that we would ensure that `WebSecurityConfig` was loaded in our existing ApplicationInitializer.
For example, if we were using Spring MVC it would be added in the `getRootConfigClasses()`

[[message-web-application-inititializer-java]]
[source,java]
----
public class MvcWebApplicationInitializer extends
		AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { WebSecurityConfig.class };
	}

	// ... other overrides ...
}
----

[[jc-httpsecurity]]
== HttpSecurity

Thus far our <<jc-hello-wsca,WebSecurityConfig>> only contains information about how to authenticate our users.
How does Spring Security know that we want to require all users to be authenticated?
How does Spring Security know we want to support form based authentication?
Actually, there is an configuration class that is being invoked behind the scenes called `WebSecurityConfigurerAdapter`.
It has a method called `configure` with the following default implementation:

[source,java]
----
protected void configure(HttpSecurity http) throws Exception {
	http
		.authorizeRequests(authorizeRequests ->
		    authorizeRequests
			    .anyRequest().authenticated()
		)
		.formLogin(withDefaults())
		.httpBasic(withDefaults());
}
----

The default configuration above:

* Ensures that any request to our application requires the user to be authenticated
* Allows users to authenticate with form based login
* Allows users to authenticate with HTTP Basic authentication
<commit_msg>Fix minor typo.<commit_after>
[[jc]]
= Java Configuration

General support for https://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java[Java Configuration] was added to Spring Framework in Spring 3.1.
Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML.

If you are familiar with the <<ns-config>> then you should find quite a few similarities between it and the Security Java Configuration support.

NOTE: Spring Security provides https://github.com/spring-projects/spring-security/tree/master/samples/javaconfig[lots of sample applications] which demonstrate the use of Spring Security Java Configuration.

== Hello Web Security Java Configuration

The first step is to create our Spring Security Java Configuration.
The configuration creates a Servlet Filter known as the `springSecurityFilterChain` which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application.
You can find the most basic example of a Spring Security Java Configuration below:

[[jc-hello-wsca]]
[source,java]
----
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;

@EnableWebSecurity
public class WebSecurityConfig {

	@Bean
	public UserDetailsService userDetailsService() {
		InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
		manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
		return manager;
	}
}
----

There really isn't much to this configuration, but it does a lot.
You can find a summary of the features below:

* Require authentication to every URL in your application
* Generate a login form for you
* Allow the user with the *Username* _user_ and the *Password* _password_ to authenticate with form based authentication
* Allow the user to logout
* 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#getUserPrincipal()]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[HttpServletRequest#isUserInRole(java.lang.String)]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)[HttpServletRequest#login(java.lang.String, java.lang.String)]
** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[HttpServletRequest#logout()]

=== AbstractSecurityWebApplicationInitializer

The next step is to register the `springSecurityFilterChain` with the war.
This can be done in Java Configuration with https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config[Spring's WebApplicationInitializer support] in a Servlet 3.0+ environment.
Not suprisingly, Spring Security provides a base class `AbstractSecurityWebApplicationInitializer` that will ensure the `springSecurityFilterChain` gets registered for you.
The way in which we use `AbstractSecurityWebApplicationInitializer` differs depending on if we are already using Spring or if Spring Security is the only Spring component in our application.

* <<abstractsecuritywebapplicationinitializer-without-existing-spring>> - Use these instructions if you are not using Spring already
* <<abstractsecuritywebapplicationinitializer-with-spring-mvc>> - Use these instructions if you are already using Spring

=== AbstractSecurityWebApplicationInitializer without Existing Spring

If you are not using Spring or Spring MVC, you will need to pass in the `WebSecurityConfig` into the superclass to ensure the configuration is picked up.
You can find an example below:

[source,java]
----
import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
	extends AbstractSecurityWebApplicationInitializer {

	public SecurityWebApplicationInitializer() {
		super(WebSecurityConfig.class);
	}
}
----

The `SecurityWebApplicationInitializer` will do the following things:

* Automatically register the springSecurityFilterChain Filter for every URL in your application
* Add a ContextLoaderListener that loads the <<jc-hello-wsca,WebSecurityConfig>>.

=== AbstractSecurityWebApplicationInitializer with Spring MVC

If we were using Spring elsewhere in our application we probably already had a `WebApplicationInitializer` that is loading our Spring Configuration.
If we use the previous configuration we would get an error.
Instead, we should register Spring Security with the existing `ApplicationContext`.
For example, if we were using Spring MVC our `SecurityWebApplicationInitializer` would look something like the following:

[source,java]
----
import org.springframework.security.web.context.*;

public class SecurityWebApplicationInitializer
	extends AbstractSecurityWebApplicationInitializer {

}
----

This would simply only register the springSecurityFilterChain Filter for every URL in your application.
After that we would ensure that `WebSecurityConfig` was loaded in our existing ApplicationInitializer.
For example, if we were using Spring MVC it would be added in the `getRootConfigClasses()`

[[message-web-application-inititializer-java]]
[source,java]
----
public class MvcWebApplicationInitializer extends
		AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { WebSecurityConfig.class };
	}

	// ... other overrides ...
}
----

[[jc-httpsecurity]]
== HttpSecurity

Thus far our <<jc-hello-wsca,WebSecurityConfig>> only contains information about how to authenticate our users.
How does Spring Security know that we want to require all users to be authenticated?
How does Spring Security know we want to support form based authentication?
Actually, there is a configuration class that is being invoked behind the scenes called `WebSecurityConfigurerAdapter`.
It has a method called `configure` with the following default implementation:

[source,java]
----
protected void configure(HttpSecurity http) throws Exception {
	http
		.authorizeRequests(authorizeRequests ->
		    authorizeRequests
			    .anyRequest().authenticated()
		)
		.formLogin(withDefaults())
		.httpBasic(withDefaults());
}
----

The default configuration above:

* Ensures that any request to our application requires the user to be authenticated
* Allows users to authenticate with form based login
* Allows users to authenticate with HTTP Basic authentication

{'fraction_non_alphanumeric': 0.08355377766307504, 'fraction_numerical': 0.0042583392476933995, 'mean_word_length': 5.7215958369470945, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 27, 'https://': 28, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7252523', 'n_tokens_mistral': 3950, 'n_tokens_neox': 3833, 'n_words': 1396}