authorize-http-requests.adoc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. .requestMatchers("/resources/**", "/signup", "/about").permitAll() // <2>
  56. .requestMatchers("/admin/**").hasRole("ADMIN") // <3>
  57. .requestMatchers("/db/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') and hasRole('DBA')")) // <4>
  58. .anyRequest().denyAll() // <5>
  59. );
  60. return http.build();
  61. }
  62. ----
  63. ====
  64. <1> There are multiple authorization rules specified.
  65. Each rule is considered in the order they were declared.
  66. <2> We specified multiple URL patterns that any user can access.
  67. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
  68. <3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".
  69. You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix.
  70. <4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA".
  71. You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix.
  72. <5> Any URL that has not already been matched on is denied access.
  73. This is a good strategy if you do not want to accidentally forget to update your authorization rules.
  74. You can take a bean-based approach by constructing your own xref:servlet/authorization/architecture.adoc#authz-delegate-authorization-manager[`RequestMatcherDelegatingAuthorizationManager`] like so:
  75. .Configure RequestMatcherDelegatingAuthorizationManager
  76. ====
  77. .Java
  78. [source,java,role="primary"]
  79. ----
  80. @Bean
  81. SecurityFilterChain web(HttpSecurity http, AuthorizationManager<RequestAuthorizationContext> access)
  82. throws AuthenticationException {
  83. http
  84. .authorizeHttpRequests((authorize) -> authorize
  85. .anyRequest().access(access)
  86. )
  87. // ...
  88. return http.build();
  89. }
  90. @Bean
  91. AuthorizationManager<RequestAuthorizationContext> requestMatcherAuthorizationManager(HandlerMappingIntrospector introspector) {
  92. MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);
  93. RequestMatcher permitAll =
  94. new AndRequestMatcher(
  95. mvcMatcherBuilder.pattern("/resources/**"),
  96. mvcMatcherBuilder.pattern("/signup"),
  97. mvcMatcherBuilder.pattern("/about"));
  98. RequestMatcher admin = mvcMatcherBuilder.pattern("/admin/**");
  99. RequestMatcher db = mvcMatcherBuilder.pattern("/db/**");
  100. RequestMatcher any = AnyRequestMatcher.INSTANCE;
  101. AuthorizationManager<HttpRequestServlet> manager = RequestMatcherDelegatingAuthorizationManager.builder()
  102. .add(permitAll, (context) -> new AuthorizationDecision(true))
  103. .add(admin, AuthorityAuthorizationManager.hasRole("ADMIN"))
  104. .add(db, AuthorityAuthorizationManager.hasRole("DBA"))
  105. .add(any, new AuthenticatedAuthorizationManager())
  106. .build();
  107. return (context) -> manager.check(context.getRequest());
  108. }
  109. ----
  110. ====
  111. You can also wire xref:servlet/authorization/architecture.adoc#authz-custom-authorization-manager[your own custom authorization managers] for any request matcher.
  112. Here is an example of mapping a custom authorization manager to the `my/authorized/endpoint`:
  113. .Custom Authorization Manager
  114. ====
  115. .Java
  116. [source,java,role="primary"]
  117. ----
  118. @Bean
  119. SecurityFilterChain web(HttpSecurity http) throws Exception {
  120. http
  121. .authorizeHttpRequests((authorize) -> authorize
  122. .requestMatchers("/my/authorized/endpoint").access(new CustomAuthorizationManager());
  123. )
  124. // ...
  125. return http.build();
  126. }
  127. ----
  128. ====
  129. Or you can provide it for all requests as seen below:
  130. .Custom Authorization Manager for All Requests
  131. ====
  132. .Java
  133. [source,java,role="primary"]
  134. ----
  135. @Bean
  136. SecurityFilterChain web(HttpSecurity http) throws Exception {
  137. http
  138. .authorizeHttpRequests((authorize) -> authorize
  139. .anyRequest().access(new CustomAuthorizationManager());
  140. )
  141. // ...
  142. return http.build();
  143. }
  144. ----
  145. ====
  146. By default, the `AuthorizationFilter` applies to all dispatcher types.
  147. We can configure Spring Security to not apply the authorization rules to all dispatcher types by using the `shouldFilterAllDispatcherTypes` method:
  148. .Set shouldFilterAllDispatcherTypes to false
  149. ====
  150. .Java
  151. [source,java,role="primary"]
  152. ----
  153. @Bean
  154. SecurityFilterChain web(HttpSecurity http) throws Exception {
  155. http
  156. .authorizeHttpRequests((authorize) -> authorize
  157. .shouldFilterAllDispatcherTypes(false)
  158. .anyRequest().authenticated()
  159. )
  160. // ...
  161. return http.build();
  162. }
  163. ----
  164. .Kotlin
  165. [source,kotlin,role="secondary"]
  166. ----
  167. @Bean
  168. open fun web(http: HttpSecurity): SecurityFilterChain {
  169. http {
  170. authorizeHttpRequests {
  171. shouldFilterAllDispatcherTypes = false
  172. authorize(anyRequest, authenticated)
  173. }
  174. }
  175. return http.build()
  176. }
  177. ----
  178. ====
  179. Instead of setting `shouldFilterAllDispatcherTypes` to `false`, the recommended approach is to customize authorization on the dispatcher types.
  180. For example, you may want to grant all access on requests with dispatcher type `ASYNC` or `FORWARD`.
  181. .Permit ASYNC and FORWARD dispatcher type
  182. ====
  183. .Java
  184. [source,java,role="primary"]
  185. ----
  186. @Bean
  187. SecurityFilterChain web(HttpSecurity http) throws Exception {
  188. http
  189. .authorizeHttpRequests((authorize) -> authorize
  190. .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.FORWARD).permitAll()
  191. .anyRequest().authenticated()
  192. )
  193. // ...
  194. return http.build();
  195. }
  196. ----
  197. .Kotlin
  198. [source,kotlin,role="secondary"]
  199. ----
  200. @Bean
  201. open fun web(http: HttpSecurity): SecurityFilterChain {
  202. http {
  203. authorizeHttpRequests {
  204. authorize(DispatcherTypeRequestMatcher(DispatcherType.ASYNC, DispatcherType.FORWARD), permitAll)
  205. authorize(anyRequest, authenticated)
  206. }
  207. }
  208. return http.build()
  209. }
  210. ----
  211. ====
  212. You can also customize it to require a specific role for a dispatcher type:
  213. .Require ADMIN for Dispatcher Type ERROR
  214. ====
  215. .Java
  216. [source,java,role="primary"]
  217. ----
  218. @Bean
  219. SecurityFilterChain web(HttpSecurity http) throws Exception {
  220. http
  221. .authorizeHttpRequests((authorize) -> authorize
  222. .dispatcherTypeMatchers(DispatcherType.ERROR).hasRole("ADMIN")
  223. .anyRequest().authenticated()
  224. )
  225. // ...
  226. return http.build();
  227. }
  228. ----
  229. .Kotlin
  230. [source,kotlin,role="secondary"]
  231. ----
  232. @Bean
  233. open fun web(http: HttpSecurity): SecurityFilterChain {
  234. http {
  235. authorizeHttpRequests {
  236. authorize(DispatcherTypeRequestMatcher(DispatcherType.ERROR), hasRole("ADMIN"))
  237. authorize(anyRequest, authenticated)
  238. }
  239. }
  240. return http.build()
  241. }
  242. ----
  243. ====
  244. == Request Matchers
  245. The `RequestMatcher` interface is used to determine if a request matches a given rule.
  246. We use `securityMatchers` to determine if a given `HttpSecurity` should be applied to a given request.
  247. The same way, we can use `requestMatchers` to determine the authorization rules that we should apply to a given request.
  248. Look at the following example:
  249. ====
  250. .Java
  251. [source,java,role="primary"]
  252. ----
  253. @Configuration
  254. @EnableWebSecurity
  255. public class SecurityConfig {
  256. @Bean
  257. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  258. http
  259. .securityMatcher("/api/**") <1>
  260. .authorizeHttpRequests(authorize -> authorize
  261. .requestMatchers("/user/**").hasRole("USER") <2>
  262. .requestMatchers("/admin/**").hasRole("ADMIN") <3>
  263. .anyRequest().authenticated() <4>
  264. )
  265. .formLogin(withDefaults());
  266. return http.build();
  267. }
  268. }
  269. ----
  270. .Kotlin
  271. [source,kotlin,role="secondary"]
  272. ----
  273. @Configuration
  274. @EnableWebSecurity
  275. open class SecurityConfig {
  276. @Bean
  277. open fun web(http: HttpSecurity): SecurityFilterChain {
  278. http {
  279. securityMatcher("/api/**") <1>
  280. authorizeHttpRequests {
  281. authorize("/user/**", hasRole("USER")) <2>
  282. authorize("/admin/**", hasRole("ADMIN")) <3>
  283. authorize(anyRequest, authenticated) <4>
  284. }
  285. }
  286. return http.build()
  287. }
  288. }
  289. ----
  290. ====
  291. <1> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`
  292. <2> Allow access to URLs that start with `/user/` to users with the `USER` role
  293. <3> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role
  294. <4> Any other request that doesn't match the rules above, will require authentication
  295. The `securityMatcher(s)` and `requestMatcher(s)` methods will decide which `RequestMatcher` implementation fits best for your application: If Spring MVC is in the classpath, then `MvcRequestMatcher` will be used, otherwise, `AntPathRequestMatcher` will be used.
  296. You can read more about the Spring MVC integration xref:servlet/integrations/mvc.adoc[here].
  297. If you want to use a specific `RequestMatcher`, just pass an implementation to the `securityMatcher` and/or `requestMatcher` methods:
  298. ====
  299. .Java
  300. [source,java,role="primary"]
  301. ----
  302. import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; <1>
  303. import static org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher;
  304. @Configuration
  305. @EnableWebSecurity
  306. public class SecurityConfig {
  307. @Bean
  308. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  309. http
  310. .securityMatcher(antMatcher("/api/**")) <2>
  311. .authorizeHttpRequests(authorize -> authorize
  312. .requestMatchers(antMatcher("/user/**")).hasRole("USER") <3>
  313. .requestMatchers(regexMatcher("/admin/.*")).hasRole("ADMIN") <4>
  314. .requestMatchers(new MyCustomRequestMatcher()).hasRole("SUPERVISOR") <5>
  315. .anyRequest().authenticated()
  316. )
  317. .formLogin(withDefaults());
  318. return http.build();
  319. }
  320. }
  321. public class MyCustomRequestMatcher implements RequestMatcher {
  322. @Override
  323. public boolean matches(HttpServletRequest request) {
  324. // ...
  325. }
  326. }
  327. ----
  328. .Kotlin
  329. [source,kotlin,role="secondary"]
  330. ----
  331. import org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher <1>
  332. import org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher
  333. @Configuration
  334. @EnableWebSecurity
  335. open class SecurityConfig {
  336. @Bean
  337. open fun web(http: HttpSecurity): SecurityFilterChain {
  338. http {
  339. securityMatcher(antMatcher("/api/**")) <2>
  340. authorizeHttpRequests {
  341. authorize(antMatcher("/user/**"), hasRole("USER")) <3>
  342. authorize(regexMatcher("/admin/**"), hasRole("ADMIN")) <4>
  343. authorize(MyCustomRequestMatcher(), hasRole("SUPERVISOR")) <5>
  344. authorize(anyRequest, authenticated)
  345. }
  346. }
  347. return http.build()
  348. }
  349. }
  350. ----
  351. ====
  352. <1> Import the static factory methods from `AntPathRequestMatcher` and `RegexRequestMatcher` to create `RequestMatcher` instances.
  353. <2> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`, using `AntPathRequestMatcher`
  354. <3> Allow access to URLs that start with `/user/` to users with the `USER` role, using `AntPathRequestMatcher`
  355. <4> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role, using `RegexRequestMatcher`
  356. <5> Allow access to URLs that match the `MyCustomRequestMatcher` to users with the `SUPERVISOR` role, using a custom `RequestMatcher`