authorize-http-requests.adoc 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. [tabs]
  15. ======
  16. Java::
  17. +
  18. [source,java,role="primary"]
  19. ----
  20. @Bean
  21. SecurityFilterChain web(HttpSecurity http) throws AuthenticationException {
  22. http
  23. .authorizeHttpRequests((authorize) -> authorize
  24. .anyRequest().authenticated();
  25. )
  26. // ...
  27. return http.build();
  28. }
  29. ----
  30. ======
  31. This improves on `authorizeRequests` in a number of ways:
  32. 1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters.
  33. This simplifies reuse and customization.
  34. 2. Delays `Authentication` lookup.
  35. 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.
  36. 3. Bean-based configuration support.
  37. 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`].
  38. .Authorize HttpServletRequest
  39. image::{figures}/authorizationfilter.png[]
  40. * 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].
  41. It wraps this in an `Supplier` in order to delay lookup.
  42. * image:{icondir}/number_2.png[] Second, it passes the `Supplier<Authentication>` and the `HttpServletRequest` to the xref:servlet/architecture.adoc#authz-authorization-manager[`AuthorizationManager`].
  43. ** image:{icondir}/number_3.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_4.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. [tabs]
  49. ======
  50. Java::
  51. +
  52. [source,java,role="primary"]
  53. ----
  54. @Bean
  55. SecurityFilterChain web(HttpSecurity http) throws Exception {
  56. http
  57. // ...
  58. .authorizeHttpRequests(authorize -> authorize // <1>
  59. .mvcMatchers("/resources/**", "/signup", "/about").permitAll() // <2>
  60. .mvcMatchers("/admin/**").hasRole("ADMIN") // <3>
  61. .mvcMatchers("/db/**").access((authentication, request) ->
  62. Optional.of(hasRole("ADMIN").check(authentication, request))
  63. .filter((decision) -> !decision.isGranted())
  64. .orElseGet(() -> hasRole("DBA").check(authentication, request));
  65. ) // <4>
  66. .anyRequest().denyAll() // <5>
  67. );
  68. return http.build();
  69. }
  70. ----
  71. ======
  72. <1> There are multiple authorization rules specified.
  73. Each rule is considered in the order they were declared.
  74. <2> We specified multiple URL patterns that any user can access.
  75. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
  76. <3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".
  77. You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix.
  78. <4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA".
  79. You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix.
  80. <5> Any URL that has not already been matched on is denied access.
  81. This is a good strategy if you do not want to accidentally forget to update your authorization rules.
  82. You can take a bean-based approach by constructing your own xref:servlet/authorization/architecture.adoc#authz-delegate-authorization-manager[`RequestMatcherDelegatingAuthorizationManager`] like so:
  83. .Configure RequestMatcherDelegatingAuthorizationManager
  84. [tabs]
  85. ======
  86. Java::
  87. +
  88. [source,java,role="primary"]
  89. ----
  90. @Bean
  91. SecurityFilterChain web(HttpSecurity http, AuthorizationManager<RequestAuthorizationContext> access)
  92. throws AuthenticationException {
  93. http
  94. .authorizeHttpRequests((authorize) -> authorize
  95. .anyRequest().access(access)
  96. )
  97. // ...
  98. return http.build();
  99. }
  100. @Bean
  101. AuthorizationManager<RequestAuthorizationContext> requestMatcherAuthorizationManager(HandlerMappingIntrospector introspector) {
  102. RequestMatcher permitAll =
  103. new AndRequestMatcher(
  104. new MvcRequestMatcher(introspector, "/resources/**"),
  105. new MvcRequestMatcher(introspector, "/signup"),
  106. new MvcRequestMatcher(introspector, "/about"));
  107. RequestMatcher admin = new MvcRequestMatcher(introspector, "/admin/**");
  108. RequestMatcher db = new MvcRequestMatcher(introspector, "/db/**");
  109. RequestMatcher any = AnyRequestMatcher.INSTANCE;
  110. AuthorizationManager<HttpRequestServlet> manager = RequestMatcherDelegatingAuthorizationManager.builder()
  111. .add(permitAll, (context) -> new AuthorizationDecision(true))
  112. .add(admin, AuthorityAuthorizationManager.hasRole("ADMIN"))
  113. .add(db, AuthorityAuthorizationManager.hasRole("DBA"))
  114. .add(any, new AuthenticatedAuthorizationManager())
  115. .build();
  116. return (context) -> manager.check(context.getRequest());
  117. }
  118. ----
  119. ======
  120. You can also wire xref:servlet/authorization/architecture.adoc#authz-custom-authorization-manager[your own custom authorization managers] for any request matcher.
  121. Here is an example of mapping a custom authorization manager to the `my/authorized/endpoint`:
  122. .Custom Authorization Manager
  123. [tabs]
  124. ======
  125. Java::
  126. +
  127. [source,java,role="primary"]
  128. ----
  129. @Bean
  130. SecurityFilterChain web(HttpSecurity http) throws Exception {
  131. http
  132. .authorizeHttpRequests((authorize) -> authorize
  133. .mvcMatchers("/my/authorized/endpoint").access(new CustomAuthorizationManager());
  134. )
  135. // ...
  136. return http.build();
  137. }
  138. ----
  139. ======
  140. Or you can provide it for all requests as seen below:
  141. .Custom Authorization Manager for All Requests
  142. [tabs]
  143. ======
  144. Java::
  145. +
  146. [source,java,role="primary"]
  147. ----
  148. @Bean
  149. SecurityFilterChain web(HttpSecurity http) throws Exception {
  150. http
  151. .authorizeHttpRequests((authorize) -> authorize
  152. .anyRequest.access(new CustomAuthorizationManager());
  153. )
  154. // ...
  155. return http.build();
  156. }
  157. ----
  158. ======
  159. By default, the `AuthorizationFilter` does not apply to `DispatcherType.ERROR` and `DispatcherType.ASYNC`.
  160. We can configure Spring Security to apply the authorization rules to all dispatcher types by using the `shouldFilterAllDispatcherTypes` method:
  161. .Set shouldFilterAllDispatcherTypes to true
  162. [tabs]
  163. ======
  164. Java::
  165. +
  166. [source,java,role="primary"]
  167. ----
  168. @Bean
  169. SecurityFilterChain web(HttpSecurity http) throws Exception {
  170. http
  171. .authorizeHttpRequests((authorize) -> authorize
  172. .shouldFilterAllDispatcherTypes(true)
  173. .anyRequest.authenticated()
  174. )
  175. // ...
  176. return http.build();
  177. }
  178. ----
  179. Kotlin::
  180. +
  181. [source,kotlin,role="secondary"]
  182. ----
  183. @Bean
  184. open fun web(http: HttpSecurity): SecurityFilterChain {
  185. http {
  186. authorizeHttpRequests {
  187. shouldFilterAllDispatcherTypes = true
  188. authorize(anyRequest, authenticated)
  189. }
  190. }
  191. return http.build()
  192. }
  193. ----
  194. ======