2
0

mvc.adoc 18 KB

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