2
0

authorize-http-requests.adoc 8.9 KB

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