mvc.adoc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. [[mvc]]
  2. = Spring MVC Integration
  3. Spring Security provides a number of optional integrations with Spring MVC.
  4. This section covers the integration in further detail.
  5. [[mvc-enablewebmvcsecurity]]
  6. == @EnableWebMvcSecurity
  7. NOTE: As of Spring Security 4.0, `@EnableWebMvcSecurity` is deprecated.
  8. The replacement is `@EnableWebSecurity` which will determine adding the Spring MVC features based upon the classpath.
  9. To enable Spring Security integration with Spring MVC add the `@EnableWebSecurity` annotation to your configuration.
  10. NOTE: Spring Security provides the configuration using Spring MVC's https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web.html#mvc-config-customize[WebMvcConfigurer].
  11. This means that if you are using more advanced options, like integrating with `WebMvcConfigurationSupport` directly, then you will need to manually provide the Spring Security configuration.
  12. [[mvc-requestmatcher]]
  13. == MvcRequestMatcher
  14. Spring Security provides deep integration with how Spring MVC matches on URLs with `MvcRequestMatcher`.
  15. This is helpful to ensure your Security rules match the logic used to handle your requests.
  16. In order to use `MvcRequestMatcher` you must place the Spring Security Configuration in the same `ApplicationContext` as your `DispatcherServlet`.
  17. This is necessary because Spring Security's `MvcRequestMatcher` expects a `HandlerMappingIntrospector` bean with the name of `mvcHandlerMappingIntrospector` to be registered by your Spring MVC configuration that is used to perform the matching.
  18. For a `web.xml` this means that you should place your configuration in the `DispatcherServlet.xml`.
  19. [source,xml]
  20. ----
  21. <listener>
  22. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  23. </listener>
  24. <!-- All Spring Configuration (both MVC and Security) are in /WEB-INF/spring/ -->
  25. <context-param>
  26. <param-name>contextConfigLocation</param-name>
  27. <param-value>/WEB-INF/spring/*.xml</param-value>
  28. </context-param>
  29. <servlet>
  30. <servlet-name>spring</servlet-name>
  31. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  32. <!-- Load from the ContextLoaderListener -->
  33. <init-param>
  34. <param-name>contextConfigLocation</param-name>
  35. <param-value></param-value>
  36. </init-param>
  37. </servlet>
  38. <servlet-mapping>
  39. <servlet-name>spring</servlet-name>
  40. <url-pattern>/</url-pattern>
  41. </servlet-mapping>
  42. ----
  43. Below `WebSecurityConfiguration` in placed in the ``DispatcherServlet``s `ApplicationContext`.
  44. [tabs]
  45. ======
  46. Java::
  47. +
  48. [source,java,role="primary"]
  49. ----
  50. public class SecurityInitializer extends
  51. AbstractAnnotationConfigDispatcherServletInitializer {
  52. @Override
  53. protected Class<?>[] getRootConfigClasses() {
  54. return null;
  55. }
  56. @Override
  57. protected Class<?>[] getServletConfigClasses() {
  58. return new Class[] { RootConfiguration.class,
  59. WebMvcConfiguration.class };
  60. }
  61. @Override
  62. protected String[] getServletMappings() {
  63. return new String[] { "/" };
  64. }
  65. }
  66. ----
  67. Kotlin::
  68. +
  69. [source,kotlin,role="secondary"]
  70. ----
  71. class SecurityInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
  72. override fun getRootConfigClasses(): Array<Class<*>>? {
  73. return null
  74. }
  75. override fun getServletConfigClasses(): Array<Class<*>> {
  76. return arrayOf(
  77. RootConfiguration::class.java,
  78. WebMvcConfiguration::class.java
  79. )
  80. }
  81. override fun getServletMappings(): Array<String> {
  82. return arrayOf("/")
  83. }
  84. }
  85. ----
  86. ======
  87. [NOTE]
  88. ====
  89. It is always recommended to provide authorization rules by matching on the `HttpServletRequest` and method security.
  90. Providing authorization rules by matching on `HttpServletRequest` is good because it happens very early in the code path and helps reduce the https://en.wikipedia.org/wiki/Attack_surface[attack surface].
  91. Method security ensures that if someone has bypassed the web authorization rules, that your application is still secured.
  92. This is what is known as https://en.wikipedia.org/wiki/Defense_in_depth_(computing)[Defence in Depth]
  93. ====
  94. Consider a controller that is mapped as follows:
  95. [tabs]
  96. ======
  97. Java::
  98. +
  99. [source,java,role="primary"]
  100. ----
  101. @RequestMapping("/admin")
  102. public String admin() {
  103. ----
  104. Kotlin::
  105. +
  106. [source,kotlin,role="secondary"]
  107. ----
  108. @RequestMapping("/admin")
  109. fun admin(): String {
  110. ----
  111. ======
  112. If we wanted to restrict access to this controller method to admin users, a developer can provide authorization rules by matching on the `HttpServletRequest` with the following:
  113. [tabs]
  114. ======
  115. Java::
  116. +
  117. [source,java,role="primary"]
  118. ----
  119. @Bean
  120. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  121. http
  122. .authorizeHttpRequests(authorize -> authorize
  123. .antMatchers("/admin").hasRole("ADMIN")
  124. );
  125. return http.build();
  126. }
  127. ----
  128. Kotlin::
  129. +
  130. [source,kotlin,role="secondary"]
  131. ----
  132. @Bean
  133. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  134. http {
  135. authorizeRequests {
  136. authorize(AntPathRequestMatcher("/admin"), hasRole("ADMIN"))
  137. }
  138. }
  139. return http.build()
  140. }
  141. ----
  142. ======
  143. or in XML
  144. [source,xml]
  145. ----
  146. <http>
  147. <intercept-url pattern="/admin" access="hasRole('ADMIN')"/>
  148. </http>
  149. ----
  150. With either configuration, the URL `/admin` will require the authenticated user to be an admin user.
  151. However, depending on our Spring MVC configuration, the URL `/admin.html` will also map to our `admin()` method.
  152. Additionally, depending on our Spring MVC configuration, the URL `/admin/` will also map to our `admin()` method.
  153. The problem is that our security rule is only protecting `/admin`.
  154. We could add additional rules for all the permutations of Spring MVC, but this would be quite verbose and tedious.
  155. Instead, we can leverage Spring Security's `MvcRequestMatcher`.
  156. The following configuration will protect the same URLs that Spring MVC will match on by using Spring MVC to match on the URL.
  157. [tabs]
  158. ======
  159. Java::
  160. +
  161. [source,java,role="primary"]
  162. ----
  163. @Bean
  164. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  165. http
  166. .authorizeHttpRequests(authorize -> authorize
  167. .mvcMatchers("/admin").hasRole("ADMIN")
  168. );
  169. // ...
  170. }
  171. ----
  172. Kotlin::
  173. +
  174. [source,kotlin,role="secondary"]
  175. ----
  176. @Bean
  177. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  178. http {
  179. authorizeRequests {
  180. authorize("/admin", hasRole("ADMIN"))
  181. }
  182. }
  183. // ...
  184. }
  185. ----
  186. ======
  187. or in XML
  188. [source,xml]
  189. ----
  190. <http request-matcher="mvc">
  191. <intercept-url pattern="/admin" access="hasRole('ADMIN')"/>
  192. </http>
  193. ----
  194. [[mvc-authentication-principal]]
  195. == @AuthenticationPrincipal
  196. Spring Security provides `AuthenticationPrincipalArgumentResolver` which can automatically resolve the current `Authentication.getPrincipal()` for Spring MVC arguments.
  197. By using `@EnableWebSecurity` you will automatically have this added to your Spring MVC configuration.
  198. If you use XML based configuration, you must add this yourself.
  199. For example:
  200. [source,xml]
  201. ----
  202. <mvc:annotation-driven>
  203. <mvc:argument-resolvers>
  204. <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
  205. </mvc:argument-resolvers>
  206. </mvc:annotation-driven>
  207. ----
  208. Once `AuthenticationPrincipalArgumentResolver` is properly configured, you can be entirely decoupled from Spring Security in your Spring MVC layer.
  209. Consider a situation where a custom `UserDetailsService` that returns an `Object` that implements `UserDetails` and your own `CustomUser` `Object`. The `CustomUser` of the currently authenticated user could be accessed using the following code:
  210. [tabs]
  211. ======
  212. Java::
  213. +
  214. [source,java,role="primary"]
  215. ----
  216. @RequestMapping("/messages/inbox")
  217. public ModelAndView findMessagesForUser() {
  218. Authentication authentication =
  219. SecurityContextHolder.getContext().getAuthentication();
  220. CustomUser custom = (CustomUser) authentication == null ? null : authentication.getPrincipal();
  221. // .. find messages for this user and return them ...
  222. }
  223. ----
  224. Kotlin::
  225. +
  226. [source,kotlin,role="secondary"]
  227. ----
  228. @RequestMapping("/messages/inbox")
  229. open fun findMessagesForUser(): ModelAndView {
  230. val authentication: Authentication = SecurityContextHolder.getContext().authentication
  231. val custom: CustomUser? = if (authentication as CustomUser == null) null else authentication.principal
  232. // .. find messages for this user and return them ...
  233. }
  234. ----
  235. ======
  236. As of Spring Security 3.2 we can resolve the argument more directly by adding an annotation. For example:
  237. [tabs]
  238. ======
  239. Java::
  240. +
  241. [source,java,role="primary"]
  242. ----
  243. import org.springframework.security.core.annotation.AuthenticationPrincipal;
  244. // ...
  245. @RequestMapping("/messages/inbox")
  246. public ModelAndView findMessagesForUser(@AuthenticationPrincipal CustomUser customUser) {
  247. // .. find messages for this user and return them ...
  248. }
  249. ----
  250. Kotlin::
  251. +
  252. [source,kotlin,role="secondary"]
  253. ----
  254. @RequestMapping("/messages/inbox")
  255. open fun findMessagesForUser(@AuthenticationPrincipal customUser: CustomUser?): ModelAndView {
  256. // .. find messages for this user and return them ...
  257. }
  258. ----
  259. ======
  260. Sometimes it may be necessary to transform the principal in some way.
  261. For example, if `CustomUser` needed to be final it could not be extended.
  262. In this situation the `UserDetailsService` might returns an `Object` that implements `UserDetails` and provides a method named `getCustomUser` to access `CustomUser`.
  263. For example, it might look like:
  264. [tabs]
  265. ======
  266. Java::
  267. +
  268. [source,java,role="primary"]
  269. ----
  270. public class CustomUserUserDetails extends User {
  271. // ...
  272. public CustomUser getCustomUser() {
  273. return customUser;
  274. }
  275. }
  276. ----
  277. Kotlin::
  278. +
  279. [source,kotlin,role="secondary"]
  280. ----
  281. class CustomUserUserDetails(
  282. username: String?,
  283. password: String?,
  284. authorities: MutableCollection<out GrantedAuthority>?
  285. ) : User(username, password, authorities) {
  286. // ...
  287. val customUser: CustomUser? = null
  288. }
  289. ----
  290. ======
  291. We could then access the `CustomUser` using a https://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html[SpEL expression] that uses `Authentication.getPrincipal()` as the root object:
  292. [tabs]
  293. ======
  294. Java::
  295. +
  296. [source,java,role="primary"]
  297. ----
  298. import org.springframework.security.core.annotation.AuthenticationPrincipal;
  299. // ...
  300. @RequestMapping("/messages/inbox")
  301. public ModelAndView findMessagesForUser(@AuthenticationPrincipal(expression = "customUser") CustomUser customUser) {
  302. // .. find messages for this user and return them ...
  303. }
  304. ----
  305. Kotlin::
  306. +
  307. [source,kotlin,role="secondary"]
  308. ----
  309. import org.springframework.security.core.annotation.AuthenticationPrincipal
  310. // ...
  311. @RequestMapping("/messages/inbox")
  312. open fun findMessagesForUser(@AuthenticationPrincipal(expression = "customUser") customUser: CustomUser?): ModelAndView {
  313. // .. find messages for this user and return them ...
  314. }
  315. ----
  316. ======
  317. We can also refer to Beans in our SpEL expressions.
  318. For example, the following could be used if we were using JPA to manage our Users and we wanted to modify and save a property on the current user.
  319. [tabs]
  320. ======
  321. Java::
  322. +
  323. [source,java,role="primary"]
  324. ----
  325. import org.springframework.security.core.annotation.AuthenticationPrincipal;
  326. // ...
  327. @PutMapping("/users/self")
  328. public ModelAndView updateName(@AuthenticationPrincipal(expression = "@jpaEntityManager.merge(#this)") CustomUser attachedCustomUser,
  329. @RequestParam String firstName) {
  330. // change the firstName on an attached instance which will be persisted to the database
  331. attachedCustomUser.setFirstName(firstName);
  332. // ...
  333. }
  334. ----
  335. Kotlin::
  336. +
  337. [source,kotlin,role="secondary"]
  338. ----
  339. import org.springframework.security.core.annotation.AuthenticationPrincipal
  340. // ...
  341. @PutMapping("/users/self")
  342. open fun updateName(
  343. @AuthenticationPrincipal(expression = "@jpaEntityManager.merge(#this)") attachedCustomUser: CustomUser,
  344. @RequestParam firstName: String?
  345. ): ModelAndView {
  346. // change the firstName on an attached instance which will be persisted to the database
  347. attachedCustomUser.setFirstName(firstName)
  348. // ...
  349. }
  350. ----
  351. ======
  352. We can further remove our dependency on Spring Security by making `@AuthenticationPrincipal` a meta annotation on our own annotation.
  353. Below we demonstrate how we could do this on an annotation named `@CurrentUser`.
  354. NOTE: It is important to realize that in order to remove the dependency on Spring Security, it is the consuming application that would create `@CurrentUser`.
  355. This step is not strictly required, but assists in isolating your dependency to Spring Security to a more central location.
  356. [tabs]
  357. ======
  358. Java::
  359. +
  360. [source,java,role="primary"]
  361. ----
  362. @Target({ElementType.PARAMETER, ElementType.TYPE})
  363. @Retention(RetentionPolicy.RUNTIME)
  364. @Documented
  365. @AuthenticationPrincipal
  366. public @interface CurrentUser {}
  367. ----
  368. Kotlin::
  369. +
  370. [source,kotlin,role="secondary"]
  371. ----
  372. @Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.TYPE)
  373. @Retention(AnnotationRetention.RUNTIME)
  374. @MustBeDocumented
  375. @AuthenticationPrincipal
  376. annotation class CurrentUser
  377. ----
  378. ======
  379. Now that `@CurrentUser` has been specified, we can use it to signal to resolve our `CustomUser` of the currently authenticated user.
  380. We have also isolated our dependency on Spring Security to a single file.
  381. [tabs]
  382. ======
  383. Java::
  384. +
  385. [source,java,role="primary"]
  386. ----
  387. @RequestMapping("/messages/inbox")
  388. public ModelAndView findMessagesForUser(@CurrentUser CustomUser customUser) {
  389. // .. find messages for this user and return them ...
  390. }
  391. ----
  392. Kotlin::
  393. +
  394. [source,kotlin,role="secondary"]
  395. ----
  396. @RequestMapping("/messages/inbox")
  397. open fun findMessagesForUser(@CurrentUser customUser: CustomUser?): ModelAndView {
  398. // .. find messages for this user and return them ...
  399. }
  400. ----
  401. ======
  402. [[mvc-async]]
  403. == Spring MVC Async Integration
  404. Spring Web MVC 3.2+ has excellent support for https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-async[Asynchronous Request Processing].
  405. With no additional configuration, Spring Security will automatically setup the `SecurityContext` to the `Thread` that invokes a `Callable` returned by your controllers.
  406. For example, the following method will automatically have its `Callable` invoked with the `SecurityContext` that was available when the `Callable` was created:
  407. [tabs]
  408. ======
  409. Java::
  410. +
  411. [source,java,role="primary"]
  412. ----
  413. @RequestMapping(method=RequestMethod.POST)
  414. public Callable<String> processUpload(final MultipartFile file) {
  415. return new Callable<String>() {
  416. public Object call() throws Exception {
  417. // ...
  418. return "someView";
  419. }
  420. };
  421. }
  422. ----
  423. Kotlin::
  424. +
  425. [source,kotlin,role="secondary"]
  426. ----
  427. @RequestMapping(method = [RequestMethod.POST])
  428. open fun processUpload(file: MultipartFile?): Callable<String> {
  429. return Callable {
  430. // ...
  431. "someView"
  432. }
  433. }
  434. ----
  435. ======
  436. [NOTE]
  437. .Associating SecurityContext to Callable's
  438. ====
  439. More technically speaking, Spring Security integrates with `WebAsyncManager`.
  440. The `SecurityContext` that is used to process the `Callable` is the `SecurityContext` that exists on the `SecurityContextHolder` at the time `startCallableProcessing` is invoked.
  441. ====
  442. There is no automatic integration with a `DeferredResult` that is returned by controllers.
  443. This is because `DeferredResult` is processed by the users and thus there is no way of automatically integrating with it.
  444. However, you can still use xref:features/integrations/concurrency.adoc#concurrency[Concurrency Support] to provide transparent integration with Spring Security.
  445. [[mvc-csrf]]
  446. == Spring MVC and CSRF Integration
  447. === Automatic Token Inclusion
  448. Spring Security will automatically xref:servlet/exploits/csrf.adoc#servlet-csrf-include[include the CSRF Token] within forms that use the https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-formtag[Spring MVC form tag].
  449. For example, the following JSP:
  450. [source,xml]
  451. ----
  452. <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
  453. xmlns:c="http://java.sun.com/jsp/jstl/core"
  454. xmlns:form="http://www.springframework.org/tags/form" version="2.0">
  455. <jsp:directive.page language="java" contentType="text/html" />
  456. <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
  457. <!-- ... -->
  458. <c:url var="logoutUrl" value="/logout"/>
  459. <form:form action="${logoutUrl}"
  460. method="post">
  461. <input type="submit"
  462. value="Log out" />
  463. <input type="hidden"
  464. name="${_csrf.parameterName}"
  465. value="${_csrf.token}"/>
  466. </form:form>
  467. <!-- ... -->
  468. </html>
  469. </jsp:root>
  470. ----
  471. Will output HTML that is similar to the following:
  472. [source,xml]
  473. ----
  474. <!-- ... -->
  475. <form action="/context/logout" method="post">
  476. <input type="submit" value="Log out"/>
  477. <input type="hidden" name="_csrf" value="f81d4fae-7dec-11d0-a765-00a0c91e6bf6"/>
  478. </form>
  479. <!-- ... -->
  480. ----
  481. [[mvc-csrf-resolver]]
  482. === Resolving the CsrfToken
  483. Spring Security provides `CsrfTokenArgumentResolver` which can automatically resolve the current `CsrfToken` for Spring MVC arguments.
  484. By using xref:servlet/configuration/java.adoc#jc-hello-wsca[@EnableWebSecurity] you will automatically have this added to your Spring MVC configuration.
  485. If you use XML based configuration, you must add this yourself.
  486. Once `CsrfTokenArgumentResolver` is properly configured, you can expose the `CsrfToken` to your static HTML based application.
  487. [tabs]
  488. ======
  489. Java::
  490. +
  491. [source,java,role="primary"]
  492. ----
  493. @RestController
  494. public class CsrfController {
  495. @RequestMapping("/csrf")
  496. public CsrfToken csrf(CsrfToken token) {
  497. return token;
  498. }
  499. }
  500. ----
  501. Kotlin::
  502. +
  503. [source,kotlin,role="secondary"]
  504. ----
  505. @RestController
  506. class CsrfController {
  507. @RequestMapping("/csrf")
  508. fun csrf(token: CsrfToken): CsrfToken {
  509. return token
  510. }
  511. }
  512. ----
  513. ======
  514. It is important to keep the `CsrfToken` a secret from other domains.
  515. This means if you are using https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS[Cross Origin Sharing (CORS)], you should **NOT** expose the `CsrfToken` to any external domains.