2
0

java.adoc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. [[jc]]
  2. = Java Configuration
  3. 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.
  4. Spring Security 3.2 introduced Java configuration to let users configure Spring Security without the use of any XML.
  5. If you are familiar with the xref:servlet/configuration/xml-namespace.adoc#ns-config[Security Namespace Configuration], you should find quite a few similarities between it and Spring Security Java configuration.
  6. [NOTE]
  7. ====
  8. Spring Security provides https://github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration[lots of sample applications] to demonstrate the use of Spring Security Java Configuration.
  9. ====
  10. [[jc-hello-wsca]]
  11. == Hello Web Security Java Configuration
  12. The first step is to create our Spring Security Java Configuration.
  13. 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.
  14. The following example shows the most basic example of a Spring Security Java Configuration:
  15. ====
  16. [source,java]
  17. ----
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.context.annotation.*;
  20. import org.springframework.security.config.annotation.authentication.builders.*;
  21. import org.springframework.security.config.annotation.web.configuration.*;
  22. @Configuration
  23. @EnableWebSecurity
  24. public class WebSecurityConfig {
  25. @Bean
  26. public UserDetailsService userDetailsService() {
  27. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
  28. manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
  29. return manager;
  30. }
  31. }
  32. ----
  33. ====
  34. This configuration is not complex or extensive, but it does a lot:
  35. * Require authentication to every URL in your application
  36. * Generate a login form for you
  37. * Let the user with a *Username* of `user` and a *Password* of `password` authenticate with form based authentication
  38. * Let the user logout
  39. * https://en.wikipedia.org/wiki/Cross-site_request_forgery[CSRF attack] prevention
  40. * https://en.wikipedia.org/wiki/Session_fixation[Session Fixation] protection
  41. * Security Header integration:
  42. ** https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security[HTTP Strict Transport Security] for secure requests
  43. ** https://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx[X-Content-Type-Options] integration
  44. ** Cache Control (which you can override later in your application to allow caching of your static resources)
  45. ** https://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx[X-XSS-Protection] integration
  46. ** X-Frame-Options integration to help prevent https://en.wikipedia.org/wiki/Clickjacking[Clickjacking]
  47. * Integration with the following Servlet API methods:
  48. ** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser()[`HttpServletRequest#getRemoteUser()`]
  49. ** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()[`HttpServletRequest#getUserPrincipal()`]
  50. ** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole(java.lang.String)[`HttpServletRequest#isUserInRole(java.lang.String)`]
  51. ** 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)`]
  52. ** https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[`HttpServletRequest#logout()`]
  53. === AbstractSecurityWebApplicationInitializer
  54. The next step is to register the `springSecurityFilterChain` with the WAR file.
  55. You can do so 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.
  56. Not surprisingly, Spring Security provides a base class (`AbstractSecurityWebApplicationInitializer`) to ensure that the `springSecurityFilterChain` gets registered for you.
  57. 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.
  58. * <<abstractsecuritywebapplicationinitializer-without-existing-spring>> - Use these instructions if you are not already using Spring
  59. * <<abstractsecuritywebapplicationinitializer-with-spring-mvc>> - Use these instructions if you are already using Spring
  60. [[abstractsecuritywebapplicationinitializer-without-existing-spring]]
  61. === AbstractSecurityWebApplicationInitializer without Existing Spring
  62. If you are not using Spring or Spring MVC, you need to pass the `WebSecurityConfig` to the superclass to ensure the configuration is picked up:
  63. ====
  64. [source,java]
  65. ----
  66. import org.springframework.security.web.context.*;
  67. public class SecurityWebApplicationInitializer
  68. extends AbstractSecurityWebApplicationInitializer {
  69. public SecurityWebApplicationInitializer() {
  70. super(WebSecurityConfig.class);
  71. }
  72. }
  73. ----
  74. ====
  75. The `SecurityWebApplicationInitializer`:
  76. * Automatically registers the `springSecurityFilterChain` Filter for every URL in your application.
  77. * Add a `ContextLoaderListener` that loads the <<jc-hello-wsca,WebSecurityConfig>>.
  78. [[abstractsecuritywebapplicationinitializer-with-spring-mvc]]
  79. === AbstractSecurityWebApplicationInitializer with Spring MVC
  80. If we use Spring elsewhere in our application, we probably already have a `WebApplicationInitializer` that is loading our Spring Configuration.
  81. If we use the previous configuration, we would get an error.
  82. Instead, we should register Spring Security with the existing `ApplicationContext`.
  83. For example, if we use Spring MVC, our `SecurityWebApplicationInitializer` could look something like the following:
  84. ====
  85. [source,java]
  86. ----
  87. import org.springframework.security.web.context.*;
  88. public class SecurityWebApplicationInitializer
  89. extends AbstractSecurityWebApplicationInitializer {
  90. }
  91. ----
  92. ====
  93. This onlys register the `springSecurityFilterChain` for every URL in your application.
  94. After that, we need to ensure that `WebSecurityConfig` was loaded in our existing `ApplicationInitializer`.
  95. For example, if we use Spring MVC it is added in the `getRootConfigClasses()`:
  96. [[message-web-application-inititializer-java]]
  97. ====
  98. [source,java]
  99. ----
  100. public class MvcWebApplicationInitializer extends
  101. AbstractAnnotationConfigDispatcherServletInitializer {
  102. @Override
  103. protected Class<?>[] getRootConfigClasses() {
  104. return new Class[] { WebSecurityConfig.class };
  105. }
  106. // ... other overrides ...
  107. }
  108. ----
  109. ====
  110. [[jc-httpsecurity]]
  111. == HttpSecurity
  112. Thus far, our <<jc-hello-wsca,`WebSecurityConfig`>> contains only information about how to authenticate our users.
  113. How does Spring Security know that we want to require all users to be authenticated?
  114. How does Spring Security know we want to support form-based authentication?
  115. Actually, there is a configuration class (called `SecurityFilterChain`) that is being invoked behind the scenes.
  116. It is configured with the following default implementation:
  117. ====
  118. [source,java]
  119. ----
  120. @Bean
  121. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  122. http
  123. .authorizeRequests(authorize -> authorize
  124. .anyRequest().authenticated()
  125. )
  126. .formLogin(withDefaults())
  127. .httpBasic(withDefaults());
  128. return http.build();
  129. }
  130. ----
  131. ====
  132. The default configuration (shown in the preceding example):
  133. * Ensures that any request to our application requires the user to be authenticated
  134. * Lets users authenticate with form based login
  135. * Lets users authenticate with HTTP Basic authentication
  136. Note that this configuration is parallels the XML Namespace configuration:
  137. ====
  138. [source,xml]
  139. ----
  140. <http>
  141. <intercept-url pattern="/**" access="authenticated"/>
  142. <form-login />
  143. <http-basic />
  144. </http>
  145. ----
  146. ====
  147. == Multiple HttpSecurity Instances
  148. We can configure multiple `HttpSecurity` instances just as we can have multiple `<http>` blocks in XML.
  149. The key is to register multiple `SecurityFilterChain` ``@Bean``s.
  150. The following example has a different configuration for URL's that start with `/api/`.
  151. ====
  152. [source,java]
  153. ----
  154. @Configuration
  155. @EnableWebSecurity
  156. public class MultiHttpSecurityConfig {
  157. @Bean <1>
  158. public UserDetailsService userDetailsService() throws Exception {
  159. // ensure the passwords are encoded properly
  160. UserBuilder users = User.withDefaultPasswordEncoder();
  161. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
  162. manager.createUser(users.username("user").password("password").roles("USER").build());
  163. manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build());
  164. return manager;
  165. }
  166. @Bean
  167. @Order(1) <2>
  168. public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
  169. http
  170. .securityMatcher("/api/**") <3>
  171. .authorizeHttpRequests(authorize -> authorize
  172. .anyRequest().hasRole("ADMIN")
  173. )
  174. .httpBasic(withDefaults());
  175. return http.build();
  176. }
  177. @Bean <4>
  178. public SecurityFilterChain formLoginFilterChain(HttpSecurity http) throws Exception {
  179. http
  180. .authorizeHttpRequests(authorize -> authorize
  181. .anyRequest().authenticated()
  182. )
  183. .formLogin(withDefaults());
  184. return http.build();
  185. }
  186. }
  187. ----
  188. <1> Configure Authentication as usual.
  189. <2> Create an instance of `SecurityFilterChain` that contains `@Order` to specify which `SecurityFilterChain` should be considered first.
  190. <3> The `http.securityMatcher` states that this `HttpSecurity` is applicable only to URLs that start with `/api/`.
  191. <4> Create another instance of `SecurityFilterChain`.
  192. If the URL does not start with `/api/`, this configuration is used.
  193. This configuration is considered after `apiFilterChain`, since it has an `@Order` value after `1` (no `@Order` defaults to last).
  194. ====
  195. [[jc-custom-dsls]]
  196. == Custom DSLs
  197. You can provide your own custom DSLs in Spring Security:
  198. ====
  199. [source,java]
  200. ----
  201. public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {
  202. private boolean flag;
  203. @Override
  204. public void init(HttpSecurity http) throws Exception {
  205. // any method that adds another configurer
  206. // must be done in the init method
  207. http.csrf().disable();
  208. }
  209. @Override
  210. public void configure(HttpSecurity http) throws Exception {
  211. ApplicationContext context = http.getSharedObject(ApplicationContext.class);
  212. // here we lookup from the ApplicationContext. You can also just create a new instance.
  213. MyFilter myFilter = context.getBean(MyFilter.class);
  214. myFilter.setFlag(flag);
  215. http.addFilterBefore(myFilter, UsernamePasswordAuthenticationFilter.class);
  216. }
  217. public MyCustomDsl flag(boolean value) {
  218. this.flag = value;
  219. return this;
  220. }
  221. public static MyCustomDsl customDsl() {
  222. return new MyCustomDsl();
  223. }
  224. }
  225. ----
  226. ====
  227. [NOTE]
  228. ====
  229. This is actually how methods like `HttpSecurity.authorizeRequests()` are implemented.
  230. ====
  231. You can then use the custom DSL:
  232. ====
  233. [source,java]
  234. ----
  235. @Configuration
  236. @EnableWebSecurity
  237. public class Config {
  238. @Bean
  239. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  240. http
  241. .apply(customDsl())
  242. .flag(true)
  243. .and()
  244. ...;
  245. return http.build();
  246. }
  247. }
  248. ----
  249. ====
  250. The code is invoked in the following order:
  251. * Code in the `Config.configure` method is invoked
  252. * Code in the `MyCustomDsl.init` method is invoked
  253. * Code in the `MyCustomDsl.configure` method is invoked
  254. If you want, you can have `HttpSecurity` add `MyCustomDsl` by default by using `SpringFactories`.
  255. For example, you can create a resource on the classpath named `META-INF/spring.factories` with the following contents:
  256. .META-INF/spring.factories
  257. ====
  258. [source]
  259. ----
  260. org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyCustomDsl
  261. ----
  262. ====
  263. You can also explicit disable the default:
  264. ====
  265. [source,java]
  266. ----
  267. @Configuration
  268. @EnableWebSecurity
  269. public class Config {
  270. @Bean
  271. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  272. http
  273. .apply(customDsl()).disable()
  274. ...;
  275. return http.build();
  276. }
  277. }
  278. ----
  279. ====
  280. [[post-processing-configured-objects]]
  281. == Post Processing Configured Objects
  282. Spring Security's Java configuration does not expose every property of every object that it configures.
  283. This simplifies the configuration for a majority of users.
  284. After all, if every property were exposed, users could use standard bean configuration.
  285. While there are good reasons to not directly expose every property, users may still need more advanced configuration options.
  286. To address this issue, Spring Security introduces the concept of an `ObjectPostProcessor`, which can be used to modify or replace many of the `Object` instances created by the Java Configuration.
  287. For example, to configure the `filterSecurityPublishAuthorizationSuccess` property on `FilterSecurityInterceptor`, you can use the following:
  288. ====
  289. [source,java]
  290. ----
  291. @Bean
  292. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  293. http
  294. .authorizeRequests(authorize -> authorize
  295. .anyRequest().authenticated()
  296. .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
  297. public <O extends FilterSecurityInterceptor> O postProcess(
  298. O fsi) {
  299. fsi.setPublishAuthorizationSuccess(true);
  300. return fsi;
  301. }
  302. })
  303. );
  304. return http.build();
  305. }
  306. ----
  307. ====