mvc.adoc 17 KB

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