2
0

authorize-requests.adoc 7.9 KB

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