2
0

kotlin.adoc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. [[kotlin-config]]
  2. = Kotlin Configuration
  3. Spring Security Kotlin configuration has been available since Spring Security 5.3.
  4. It lets users configure Spring Security by using a native Kotlin DSL.
  5. [NOTE]
  6. ====
  7. Spring Security provides https://github.com/spring-projects/spring-security-samples/tree/main/servlet/spring-boot/kotlin/hello-security[a sample application] to demonstrate the use of Spring Security Kotlin Configuration.
  8. ====
  9. [[kotlin-config-httpsecurity]]
  10. == HttpSecurity
  11. How does Spring Security know that we want to require all users to be authenticated?
  12. How does Spring Security know we want to support form-based authentication?
  13. There is a configuration class (called `SecurityFilterChain`) that is being invoked behind the scenes.
  14. It is configured with the following default implementation:
  15. [source,kotlin]
  16. ----
  17. import org.springframework.security.config.annotation.web.invoke
  18. @Bean
  19. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  20. http {
  21. authorizeHttpRequests {
  22. authorize(anyRequest, authenticated)
  23. }
  24. formLogin { }
  25. httpBasic { }
  26. }
  27. return http.build()
  28. }
  29. ----
  30. [NOTE]
  31. Make sure to import the `org.springframework.security.config.annotation.web.invoke` function to enable the Kotlin DSL in your class, as the IDE will not always auto-import the method, causing compilation issues.
  32. The default configuration (shown in the preceding example):
  33. * Ensures that any request to our application requires the user to be authenticated
  34. * Lets users authenticate with form-based login
  35. * Lets users authenticate with HTTP Basic authentication
  36. Note that this configuration parallels the XML namespace configuration:
  37. [source,xml]
  38. ----
  39. <http>
  40. <intercept-url pattern="/**" access="authenticated"/>
  41. <form-login />
  42. <http-basic />
  43. </http>
  44. ----
  45. === Multiple HttpSecurity Instances
  46. To effectively manage security in an application where certain areas need different protection, we can employ multiple filter chains alongside the `securityMatcher` DSL method.
  47. This approach allows us to define distinct security configurations tailored to specific parts of the application, enhancing overall application security and control.
  48. We can configure multiple `HttpSecurity` instances just as we can have multiple `<http>` blocks in XML.
  49. The key is to register multiple `SecurityFilterChain` ``@Bean``s.
  50. The following example has a different configuration for URLs that begin with `/api/`:
  51. [[multiple-httpsecurity-instances-kotlin]]
  52. [source,kotlin]
  53. ----
  54. import org.springframework.security.config.annotation.web.invoke
  55. @Configuration
  56. @EnableWebSecurity
  57. class MultiHttpSecurityConfig {
  58. @Bean <1>
  59. open fun userDetailsService(): UserDetailsService {
  60. val users = User.withDefaultPasswordEncoder()
  61. val manager = InMemoryUserDetailsManager()
  62. manager.createUser(users.username("user").password("password").roles("USER").build())
  63. manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build())
  64. return manager
  65. }
  66. @Bean
  67. @Order(1) <2>
  68. open fun apiFilterChain(http: HttpSecurity): SecurityFilterChain {
  69. http {
  70. securityMatcher("/api/**") <3>
  71. authorizeHttpRequests {
  72. authorize(anyRequest, hasRole("ADMIN"))
  73. }
  74. httpBasic { }
  75. }
  76. return http.build()
  77. }
  78. @Bean <4>
  79. open fun formLoginFilterChain(http: HttpSecurity): SecurityFilterChain {
  80. http {
  81. authorizeHttpRequests {
  82. authorize(anyRequest, authenticated)
  83. }
  84. formLogin { }
  85. }
  86. return http.build()
  87. }
  88. }
  89. ----
  90. <1> Configure Authentication as usual.
  91. <2> Create an instance of `SecurityFilterChain` that contains `@Order` to specify which `SecurityFilterChain` should be considered first.
  92. <3> The `http.securityMatcher()` states that this `HttpSecurity` is applicable only to URLs that begin with `/api/`.
  93. <4> Create another instance of `SecurityFilterChain`.
  94. If the URL does not begin with `/api/`, this configuration is used.
  95. This configuration is considered after `apiFilterChain`, since it has an `@Order` value after `1` (no `@Order` defaults to last).
  96. === Choosing `securityMatcher` or `requestMatchers`
  97. A common question is:
  98. > What is the difference between the `http.securityMatcher()` method and `requestMatchers()` used for request authorization (i.e. inside of `http.authorizeHttpRequests()`)?
  99. To answer this question, it helps to understand that each `HttpSecurity` instance used to build a `SecurityFilterChain` contains a `RequestMatcher` to match incoming requests.
  100. If a request does not match a `SecurityFilterChain` with higher priority (e.g. `@Order(1)`), the request can be tried against a filter chain with lower priority (e.g. no `@Order`).
  101. [NOTE]
  102. ====
  103. The matching logic for multiple filter chains is performed by the xref:servlet/architecture.adoc#servlet-filterchainproxy[`FilterChainProxy`].
  104. ====
  105. The default `RequestMatcher` matches *any request* to ensure Spring Security protects *all requests by default*.
  106. [NOTE]
  107. ====
  108. Specifying a `securityMatcher` overrides this default.
  109. ====
  110. [WARNING]
  111. ====
  112. If no filter chain matches a particular request, the request is *not protected* by Spring Security.
  113. ====
  114. The following example demonstrates a single filter chain that only protects requests that begin with `/secured/`:
  115. [[choosing-security-matcher-request-matchers-kotlin]]
  116. [source,kotlin]
  117. ----
  118. import org.springframework.security.config.annotation.web.invoke
  119. @Configuration
  120. @EnableWebSecurity
  121. class PartialSecurityConfig {
  122. @Bean
  123. open fun userDetailsService(): UserDetailsService {
  124. // ...
  125. }
  126. @Bean
  127. open fun securedFilterChain(http: HttpSecurity): SecurityFilterChain {
  128. http {
  129. securityMatcher("/secured/**") <1>
  130. authorizeHttpRequests {
  131. authorize("/secured/user", hasRole("USER")) <2>
  132. authorize("/secured/admin", hasRole("ADMIN")) <3>
  133. authorize(anyRequest, authenticated) <4>
  134. }
  135. httpBasic { }
  136. formLogin { }
  137. }
  138. return http.build()
  139. }
  140. }
  141. ----
  142. <1> Requests that begin with `/secured/` will be protected but any other requests are not protected.
  143. <2> Requests to `/secured/user` require the `ROLE_USER` authority.
  144. <3> Requests to `/secured/admin` require the `ROLE_ADMIN` authority.
  145. <4> Any other requests (such as `/secured/other`) simply require an authenticated user.
  146. [TIP]
  147. ====
  148. It is _recommended_ to provide a `SecurityFilterChain` that does not specify any `securityMatcher` to ensure the entire application is protected, as demonstrated in the <<multiple-httpsecurity-instances-kotlin,earlier example>>.
  149. ====
  150. Notice that the `requestMatchers` method only applies to individual authorization rules.
  151. Each request listed there must also match the overall `securityMatcher` for this particular `HttpSecurity` instance used to create the `SecurityFilterChain`.
  152. Using `anyRequest()` in this example matches all other requests within this particular `SecurityFilterChain` (which must begin with `/secured/`).
  153. [NOTE]
  154. ====
  155. See xref:servlet/authorization/authorize-http-requests.adoc[Authorize HttpServletRequests] for more information on `requestMatchers`.
  156. ====
  157. === `SecurityFilterChain` Endpoints
  158. Several filters in the `SecurityFilterChain` directly provide endpoints, such as the `UsernamePasswordAuthenticationFilter` which is set up by `http.formLogin()` and provides the `POST /login` endpoint.
  159. In the <<choosing-security-matcher-request-matchers-kotlin,above example>>, the `/login` endpoint is not matched by `http.securityMatcher("/secured/**")` and therefore that application would not have any `GET /login` or `POST /login` endpoint.
  160. Such requests would return `404 Not Found`.
  161. This is often surprising to users.
  162. Specifying `http.securityMatcher()` affects what requests are matched by that `SecurityFilterChain`.
  163. However, it does not automatically affect endpoints provided by the filter chain.
  164. In such cases, you may need to customize the URL of any endpoints you would like the filter chain to provide.
  165. The following example demonstrates a configuration that secures requests that begin with `/secured/` and denies all other requests, while also customizing endpoints provided by the `SecurityFilterChain`:
  166. [[security-filter-chain-endpoints-kotlin]]
  167. [source,kotlin]
  168. ----
  169. import org.springframework.security.config.annotation.web.invoke
  170. @Configuration
  171. @EnableWebSecurity
  172. class SecuredSecurityConfig {
  173. @Bean
  174. open fun userDetailsService(): UserDetailsService {
  175. // ...
  176. }
  177. @Bean
  178. @Order(1)
  179. open fun securedFilterChain(http: HttpSecurity): SecurityFilterChain {
  180. http {
  181. securityMatcher("/secured/**") <1>
  182. authorizeHttpRequests {
  183. authorize(anyRequest, authenticated) <2>
  184. }
  185. formLogin { <3>
  186. loginPage = "/secured/login"
  187. loginProcessingUrl = "/secured/login"
  188. permitAll = true
  189. }
  190. logout { <4>
  191. logoutUrl = "/secured/logout"
  192. logoutSuccessUrl = "/secured/login?logout"
  193. permitAll = true
  194. }
  195. }
  196. return http.build()
  197. }
  198. @Bean
  199. open fun defaultFilterChain(http: HttpSecurity): SecurityFilterChain {
  200. http {
  201. authorizeHttpRequests {
  202. authorize(anyRequest, denyAll) <5>
  203. }
  204. }
  205. return http.build()
  206. }
  207. }
  208. ----
  209. <1> Requests that begin with `/secured/` will be protected by this filter chain.
  210. <2> Requests that begin with `/secured/` require an authenticated user.
  211. <3> Customize form login to prefix URLs with `/secured/`.
  212. <4> Customize logout to prefix URLs with `/secured/`.
  213. <5> All other requests will be denied.
  214. [NOTE]
  215. ====
  216. This example customizes the login and logout pages, which disables Spring Security's generated pages.
  217. You must xref:servlet/authentication/passwords/form.adoc#servlet-authentication-form-custom[provide your own] custom endpoints for `GET /secured/login` and `GET /secured/logout`.
  218. Note that Spring Security still provides `POST /secured/login` and `POST /secured/logout` endpoints for you.
  219. ====
  220. === Real World Example
  221. The following example demonstrates a slightly more real-world configuration putting all of these elements together:
  222. [[real-world-example-kotlin]]
  223. [source,kotlin]
  224. ----
  225. import org.springframework.security.config.annotation.web.invoke
  226. @Configuration
  227. @EnableWebSecurity
  228. class BankingSecurityConfig {
  229. @Bean <1>
  230. open fun userDetailsService(): UserDetailsService {
  231. val users = User.withDefaultPasswordEncoder()
  232. val manager = InMemoryUserDetailsManager()
  233. manager.createUser(users.username("user1").password("password").roles("USER", "VIEW_BALANCE").build())
  234. manager.createUser(users.username("user2").password("password").roles("USER").build())
  235. manager.createUser(users.username("admin").password("password").roles("ADMIN").build())
  236. return manager
  237. }
  238. @Bean
  239. @Order(1) <2>
  240. open fun approvalsSecurityFilterChain(http: HttpSecurity): SecurityFilterChain {
  241. val approvalsPaths = arrayOf("/accounts/approvals/**", "/loans/approvals/**", "/credit-cards/approvals/**")
  242. http {
  243. securityMatcher(*approvalsPaths)
  244. authorizeHttpRequests {
  245. authorize(anyRequest, hasRole("ADMIN"))
  246. }
  247. httpBasic { }
  248. }
  249. return http.build()
  250. }
  251. @Bean
  252. @Order(2) <3>
  253. open fun bankingSecurityFilterChain(http: HttpSecurity): SecurityFilterChain {
  254. val bankingPaths = arrayOf("/accounts/**", "/loans/**", "/credit-cards/**", "/balances/**")
  255. val viewBalancePaths = arrayOf("/balances/**")
  256. http {
  257. securityMatcher(*bankingPaths)
  258. authorizeHttpRequests {
  259. authorize(viewBalancePaths, hasRole("VIEW_BALANCE"))
  260. authorize(anyRequest, hasRole("USER"))
  261. }
  262. }
  263. return http.build()
  264. }
  265. @Bean <4>
  266. open fun defaultSecurityFilterChain(http: HttpSecurity): SecurityFilterChain {
  267. val allowedPaths = arrayOf("/", "/user-login", "/user-logout", "/notices", "/contact", "/register")
  268. http {
  269. authorizeHttpRequests {
  270. authorize(allowedPaths, permitAll)
  271. authorize(anyRequest, authenticated)
  272. }
  273. formLogin {
  274. loginPage = "/user-login"
  275. loginProcessingUrl = "/user-login"
  276. }
  277. logout {
  278. logoutUrl = "/user-logout"
  279. logoutSuccessUrl = "/?logout"
  280. }
  281. }
  282. return http.build()
  283. }
  284. }
  285. ----
  286. <1> Begin by configuring authentication settings.
  287. <2> Define a `SecurityFilterChain` instance with `@Order(1)`, which means that this filter chain will have the highest priority.
  288. This filter chain applies only to requests that begin with `/accounts/approvals/`, `/loans/approvals/` or `/credit-cards/approvals/`.
  289. Requests to this filter chain require the `ROLE_ADMIN` authority and allow HTTP Basic Authentication.
  290. <3> Next, create another `SecurityFilterChain` instance with `@Order(2)` which will be considered second.
  291. This filter chain applies only to requests that begin with `/accounts/`, `/loans/`, `/credit-cards/`, or `/balances/`.
  292. Notice that because this filter chain is second, any requests that include `/approvals/` will match the previous filter chain and will *not* be matched by this filter chain.
  293. Requests to this filter chain require the `ROLE_USER` authority.
  294. This filter chain does not define any authentication because the next (default) filter chain contains that configuration.
  295. <4> Lastly, create an additional `SecurityFilterChain` instance without an `@Order` annotation.
  296. This configuration will handle requests not covered by the other filter chains and will be processed last (no `@Order` defaults to last).
  297. Requests that match `/`, `/user-login`, `/user-logout`, `/notices`, `/contact` and `/register` allow access without authentication.
  298. Any other requests require the user to be authenticated to access any URL not explicitly allowed or protected by other filter chains.