authorize-http-requests.adoc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. [[servlet-authorization-authorizationfilter]]
  2. = Authorize HttpServletRequests with AuthorizationFilter
  3. :figures: servlet/authorization
  4. 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.
  5. [NOTE]
  6. `AuthorizationFilter` supersedes xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`].
  7. To remain backward compatible, `FilterSecurityInterceptor` remains the default.
  8. This section discusses how `AuthorizationFilter` works and how to override the default configuration.
  9. The {security-api-url}org/springframework/security/web/access/intercept/AuthorizationFilter.html[`AuthorizationFilter`] provides xref:servlet/authorization/index.adoc#servlet-authorization[authorization] for ``HttpServletRequest``s.
  10. 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].
  11. You can override the default when you declare a `SecurityFilterChain`.
  12. Instead of using xref:servlet/authorization/authorize-http-requests.adoc#servlet-authorize-requests-defaults[`authorizeRequests`], use `authorizeHttpRequests`, like so:
  13. .Use authorizeHttpRequests
  14. ====
  15. .Java
  16. [source,java,role="primary"]
  17. ----
  18. @Bean
  19. SecurityFilterChain web(HttpSecurity http) throws AuthenticationException {
  20. http
  21. .authorizeHttpRequests((authorize) -> authorize
  22. .anyRequest().authenticated();
  23. )
  24. // ...
  25. return http.build();
  26. }
  27. ----
  28. ====
  29. This improves on `authorizeRequests` in a number of ways:
  30. 1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters.
  31. This simplifies reuse and customization.
  32. 2. Delays `Authentication` lookup.
  33. Instead of the authentication needing to be looked up for every request, it will only look it up in requests where an authorization decision requires authentication.
  34. 3. Bean-based configuration support.
  35. When `authorizeHttpRequests` is used instead of `authorizeRequests`, then {security-api-url}org/springframework/security/web/access/intercept/AuthorizationFilter.html[`AuthorizationFilter`] is used instead of xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`].
  36. .Authorize HttpServletRequest
  37. image::{figures}/authorizationfilter.png[]
  38. * image:{icondir}/number_1.png[] First, the `AuthorizationFilter` obtains an xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder].
  39. It wraps this in an `Supplier` in order to delay lookup.
  40. * image:{icondir}/number_2.png[] Second, `AuthorizationFilter` creates a {security-api-url}org/springframework/security/web/FilterInvocation.html[`FilterInvocation`] from the `HttpServletRequest`, `HttpServletResponse`, and `FilterChain`.
  41. // FIXME: link to FilterInvocation
  42. * image:{icondir}/number_3.png[] Next, it passes the `Supplier<Authentication>` and `FilterInvocation` to the xref:servlet/architecture.adoc#authz-authorization-manager[`AuthorizationManager`].
  43. ** image:{icondir}/number_4.png[] If authorization is denied, an `AccessDeniedException` is thrown.
  44. In this case the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`.
  45. ** image:{icondir}/number_5.png[] If access is granted, `AuthorizationFilter` continues with the xref:servlet/architecture.adoc#servlet-filters-review[FilterChain] which allows the application to process normally.
  46. We can configure Spring Security to have different rules by adding more rules in order of precedence.
  47. .Authorize Requests
  48. ====
  49. .Java
  50. [source,java,role="primary"]
  51. ----
  52. @Bean
  53. SecurityFilterChain web(HttpSecurity http) throws Exception {
  54. http
  55. // ...
  56. .authorizeHttpRequests(authorize -> authorize // <1>
  57. .mvcMatchers("/resources/**", "/signup", "/about").permitAll() // <2>
  58. .mvcMatchers("/admin/**").hasRole("ADMIN") // <3>
  59. .mvcMatchers("/db/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') and hasRole('DBA')")) // <4>
  60. .anyRequest().denyAll() // <5>
  61. );
  62. return http.build();
  63. }
  64. ----
  65. ====
  66. <1> There are multiple authorization rules specified.
  67. Each rule is considered in the order they were declared.
  68. <2> We specified multiple URL patterns that any user can access.
  69. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
  70. <3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".
  71. You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix.
  72. <4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA".
  73. You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix.
  74. <5> Any URL that has not already been matched on is denied access.
  75. This is a good strategy if you do not want to accidentally forget to update your authorization rules.
  76. You can take a bean-based approach by constructing your own xref:servlet/authorization/architecture.adoc#authz-delegate-authorization-manager[`RequestMatcherDelegatingAuthorizationManager`] like so:
  77. .Configure RequestMatcherDelegatingAuthorizationManager
  78. ====
  79. .Java
  80. [source,java,role="primary"]
  81. ----
  82. @Bean
  83. SecurityFilterChain web(HttpSecurity http, AuthorizationManager<RequestAuthorizationContext> access)
  84. throws AuthenticationException {
  85. http
  86. .authorizeHttpRequests((authorize) -> authorize
  87. .anyRequest().access(access)
  88. )
  89. // ...
  90. return http.build();
  91. }
  92. @Bean
  93. AuthorizationManager<RequestAuthorizationContext> requestMatcherAuthorizationManager(HandlerMappingIntrospector introspector) {
  94. MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);
  95. RequestMatcher permitAll =
  96. new AndRequestMatcher(
  97. mvcMatcherBuilder.pattern("/resources/**"),
  98. mvcMatcherBuilder.pattern("/signup"),
  99. mvcMatcherBuilder.pattern("/about"));
  100. RequestMatcher admin = mvcMatcherBuilder.pattern("/admin/**");
  101. RequestMatcher db = mvcMatcherBuilder.pattern("/db/**");
  102. RequestMatcher any = AnyRequestMatcher.INSTANCE;
  103. AuthorizationManager<HttpRequestServlet> manager = RequestMatcherDelegatingAuthorizationManager.builder()
  104. .add(permitAll, (context) -> new AuthorizationDecision(true))
  105. .add(admin, AuthorityAuthorizationManager.hasRole("ADMIN"))
  106. .add(db, AuthorityAuthorizationManager.hasRole("DBA"))
  107. .add(any, new AuthenticatedAuthorizationManager())
  108. .build();
  109. return (context) -> manager.check(context.getRequest());
  110. }
  111. ----
  112. ====
  113. You can also wire xref:servlet/authorization/architecture.adoc#authz-custom-authorization-manager[your own custom authorization managers] for any request matcher.
  114. Here is an example of mapping a custom authorization manager to the `my/authorized/endpoint`:
  115. .Custom Authorization Manager
  116. ====
  117. .Java
  118. [source,java,role="primary"]
  119. ----
  120. @Bean
  121. SecurityFilterChain web(HttpSecurity http) throws Exception {
  122. http
  123. .authorizeHttpRequests((authorize) -> authorize
  124. .mvcMatchers("/my/authorized/endpoint").access(new CustomAuthorizationManager());
  125. )
  126. // ...
  127. return http.build();
  128. }
  129. ----
  130. ====
  131. Or you can provide it for all requests as seen below:
  132. .Custom Authorization Manager for All Requests
  133. ====
  134. .Java
  135. [source,java,role="primary"]
  136. ----
  137. @Bean
  138. SecurityFilterChain web(HttpSecurity http) throws Exception {
  139. http
  140. .authorizeHttpRequests((authorize) -> authorize
  141. .anyRequest().access(new CustomAuthorizationManager());
  142. )
  143. // ...
  144. return http.build();
  145. }
  146. ----
  147. ====
  148. By default, the `AuthorizationFilter` applies to all dispatcher types.
  149. We can configure Spring Security to not apply the authorization rules to all dispatcher types by using the `shouldFilterAllDispatcherTypes` method:
  150. .Set shouldFilterAllDispatcherTypes to false
  151. ====
  152. .Java
  153. [source,java,role="primary"]
  154. ----
  155. @Bean
  156. SecurityFilterChain web(HttpSecurity http) throws Exception {
  157. http
  158. .authorizeHttpRequests((authorize) -> authorize
  159. .shouldFilterAllDispatcherTypes(false)
  160. .anyRequest().authenticated()
  161. )
  162. // ...
  163. return http.build();
  164. }
  165. ----
  166. .Kotlin
  167. [source,kotlin,role="secondary"]
  168. ----
  169. @Bean
  170. open fun web(http: HttpSecurity): SecurityFilterChain {
  171. http {
  172. authorizeHttpRequests {
  173. shouldFilterAllDispatcherTypes = false
  174. authorize(anyRequest, authenticated)
  175. }
  176. }
  177. return http.build()
  178. }
  179. ----
  180. ====
  181. Instead of setting `shouldFilterAllDispatcherTypes` to `false`, the recommended approach is to customize authorization on the dispatcher types.
  182. For example, you may want to grant all access on requests with dispatcher type `ASYNC` or `FORWARD`.
  183. .Permit ASYNC and FORWARD dispatcher type
  184. ====
  185. .Java
  186. [source,java,role="primary"]
  187. ----
  188. @Bean
  189. SecurityFilterChain web(HttpSecurity http) throws Exception {
  190. http
  191. .authorizeHttpRequests((authorize) -> authorize
  192. .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.FORWARD).permitAll()
  193. .anyRequest().authenticated()
  194. )
  195. // ...
  196. return http.build();
  197. }
  198. ----
  199. .Kotlin
  200. [source,kotlin,role="secondary"]
  201. ----
  202. @Bean
  203. open fun web(http: HttpSecurity): SecurityFilterChain {
  204. http {
  205. authorizeHttpRequests {
  206. authorize(DispatcherTypeRequestMatcher(DispatcherType.ASYNC, DispatcherType.FORWARD), permitAll)
  207. authorize(anyRequest, authenticated)
  208. }
  209. }
  210. return http.build()
  211. }
  212. ----
  213. ====
  214. You can also customize it to require a specific role for a dispatcher type:
  215. .Require ADMIN for Dispatcher Type ERROR
  216. ====
  217. .Java
  218. [source,java,role="primary"]
  219. ----
  220. @Bean
  221. SecurityFilterChain web(HttpSecurity http) throws Exception {
  222. http
  223. .authorizeHttpRequests((authorize) -> authorize
  224. .dispatcherTypeMatchers(DispatcherType.ERROR).hasRole("ADMIN")
  225. .anyRequest().authenticated()
  226. )
  227. // ...
  228. return http.build();
  229. }
  230. ----
  231. .Kotlin
  232. [source,kotlin,role="secondary"]
  233. ----
  234. @Bean
  235. open fun web(http: HttpSecurity): SecurityFilterChain {
  236. http {
  237. authorizeHttpRequests {
  238. authorize(DispatcherTypeRequestMatcher(DispatcherType.ERROR), hasRole("ADMIN"))
  239. authorize(anyRequest, authenticated)
  240. }
  241. }
  242. return http.build()
  243. }
  244. ----
  245. ====