mvc.adoc 17 KB

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