authorize-requests.adoc 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. [[servlet-authorization-filtersecurityinterceptor]]
  2. = Authorize HttpServletRequest with FilterSecurityInterceptor
  3. :figures: servlet/authorization
  4. [NOTE]
  5. ====
  6. `FilterSecurityInterceptor` is in the process of being replaced by xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`].
  7. Consider using that instead.
  8. ====
  9. This section builds on xref:servlet/architecture.adoc#servlet-architecture[Servlet Architecture and Implementation] by digging deeper into how xref:servlet/authorization/index.adoc#servlet-authorization[authorization] works within Servlet-based applications.
  10. The {security-api-url}org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html[`FilterSecurityInterceptor`] provides xref:servlet/authorization/index.adoc#servlet-authorization[authorization] for `HttpServletRequest` instances.
  11. It is inserted into the xref:servlet/architecture.adoc#servlet-filterchainproxy[FilterChainProxy] as one of the xref:servlet/architecture.adoc#servlet-security-filters[Security Filters].
  12. The following image shows the role of `FilterSecurityInterceptor`:
  13. .Authorize HttpServletRequest
  14. image::{figures}/filtersecurityinterceptor.png[]
  15. image:{icondir}/number_1.png[] The `FilterSecurityInterceptor` obtains an xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder].
  16. image:{icondir}/number_2.png[] `FilterSecurityInterceptor` creates a {security-api-url}org/springframework/security/web/FilterInvocation.html[`FilterInvocation`] from the `HttpServletRequest`, `HttpServletResponse`, and `FilterChain` that are passed into the `FilterSecurityInterceptor`.
  17. image:{icondir}/number_3.png[] It passes the `FilterInvocation` to `SecurityMetadataSource` to get the ``ConfigAttribute``s.
  18. image:{icondir}/number_4.png[] It passes the `Authentication`, `FilterInvocation`, and ``ConfigAttribute``s to the `AccessDecisionManager`.
  19. image:{icondir}/number_5.png[] If authorization is denied, an `AccessDeniedException` is thrown.
  20. In this case, the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`.
  21. image:{icondir}/number_6.png[] If access is granted, `FilterSecurityInterceptor` continues with the xref:servlet/architecture.adoc#servlet-filters-review[`FilterChain`], which lets the application process normally.
  22. // configuration (xml/java)
  23. By default, Spring Security's authorization requires all requests to be authenticated.
  24. The following listing shows the explicit configuration:
  25. [[servlet-authorize-requests-defaults]]
  26. .Every Request Must be Authenticated
  27. [tabs]
  28. ======
  29. Java::
  30. +
  31. [source,java,role="primary"]
  32. ----
  33. @Bean
  34. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  35. http
  36. // ...
  37. .authorizeRequests(authorize -> authorize
  38. .anyRequest().authenticated()
  39. );
  40. return http.build();
  41. }
  42. ----
  43. XML::
  44. +
  45. [source,xml,role="secondary"]
  46. ----
  47. <http>
  48. <!-- ... -->
  49. <intercept-url pattern="/**" access="authenticated"/>
  50. </http>
  51. ----
  52. Kotlin::
  53. +
  54. [source,kotlin,role="secondary"]
  55. ----
  56. @Bean
  57. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  58. http {
  59. // ...
  60. authorizeRequests {
  61. authorize(anyRequest, authenticated)
  62. }
  63. }
  64. return http.build()
  65. }
  66. ----
  67. ======
  68. We can configure Spring Security to have different rules by adding more rules in order of precedence:
  69. .Authorize Requests
  70. [tabs]
  71. ======
  72. Java::
  73. +
  74. [source,java,role="primary"]
  75. ----
  76. @Bean
  77. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  78. http
  79. // ...
  80. .authorizeRequests(authorize -> authorize // <1>
  81. .requestMatchers("/resources/**", "/signup", "/about").permitAll() // <2>
  82. .requestMatchers("/admin/**").hasRole("ADMIN") // <3>
  83. .requestMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") // <4>
  84. .anyRequest().denyAll() // <5>
  85. );
  86. return http.build();
  87. }
  88. ----
  89. XML::
  90. +
  91. [source,xml,role="secondary"]
  92. ----
  93. <http> <!--1-->
  94. <!-- ... -->
  95. <!--2-->
  96. <intercept-url pattern="/resources/**" access="permitAll"/>
  97. <intercept-url pattern="/signup" access="permitAll"/>
  98. <intercept-url pattern="/about" access="permitAll"/>
  99. <intercept-url pattern="/admin/**" access="hasRole('ADMIN')"/> <!--3-->
  100. <intercept-url pattern="/db/**" access="hasRole('ADMIN') and hasRole('DBA')"/> <!--4-->
  101. <intercept-url pattern="/**" access="denyAll"/> <!--5-->
  102. </http>
  103. ----
  104. Kotlin::
  105. +
  106. [source,kotlin,role="secondary"]
  107. ----
  108. @Bean
  109. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  110. http {
  111. authorizeRequests { // <1>
  112. authorize("/resources/**", permitAll) // <2>
  113. authorize("/signup", permitAll)
  114. authorize("/about", permitAll)
  115. authorize("/admin/**", hasRole("ADMIN")) // <3>
  116. authorize("/db/**", "hasRole('ADMIN') and hasRole('DBA')") // <4>
  117. authorize(anyRequest, denyAll) // <5>
  118. }
  119. }
  120. return http.build()
  121. }
  122. ----
  123. ======
  124. <1> There are multiple authorization rules specified.
  125. Each rule is considered in the order they were declared.
  126. <2> We specified multiple URL patterns that any user can access.
  127. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
  128. <3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".
  129. You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix.
  130. <4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA".
  131. You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix.
  132. <5> Any URL that has not already been matched on is denied access.
  133. This is a good strategy if you do not want to accidentally forget to update your authorization rules.
  134. [[filtersecurityinterceptor-every-request]]
  135. == Configure FilterSecurityInterceptor with Dispatcher Types
  136. By default, the `FilterSecurityInterceptor` applies to every request.
  137. This means that if a request is dispatched from a request that was already filtered, the `FilterSecurityInterceptor` will perform the same authorization checks on the dispatched request.
  138. In some scenarios, you may not want to apply authorization on some dispatcher types:
  139. .Permit ASYNC and ERROR dispatcher types
  140. [tabs]
  141. ======
  142. Java::
  143. +
  144. [source,java,role="primary"]
  145. ----
  146. @Bean
  147. SecurityFilterChain web(HttpSecurity http) throws Exception {
  148. http
  149. .authorizeRequests((authorize) -> authorize
  150. .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.ERROR).permitAll()
  151. .anyRequest.authenticated()
  152. )
  153. // ...
  154. return http.build();
  155. }
  156. ----
  157. XML::
  158. +
  159. [source,xml,role="secondary"]
  160. ----
  161. <http auto-config="true">
  162. <intercept-url request-matcher-ref="dispatcherTypeMatcher" access="permitAll" />
  163. <intercept-url pattern="/**" access="authenticated"/>
  164. </http>
  165. <b:bean id="dispatcherTypeMatcher" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
  166. <b:constructor-arg value="ASYNC"/>
  167. <b:constructor-arg value="ERROR"/>
  168. </b:bean>
  169. ----
  170. ======