authorize-http-requests.adoc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. // .requestMatchers("/db/**").access(AuthorizationManagers.allOf(AuthorityAuthorizationManager.hasRole("ADMIN"), AuthorityAuthorizationManager.hasRole("DBA"))) // <5>
  59. .anyRequest().denyAll() // <6>
  60. );
  61. return http.build();
  62. }
  63. ----
  64. ====
  65. <1> There are multiple authorization rules specified.
  66. Each rule is considered in the order they were declared.
  67. <2> We specified multiple URL patterns that any user can access.
  68. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
  69. <3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".
  70. You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix.
  71. <4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA".
  72. You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix.
  73. <5> The same rule from 4, could be written by combining multiple `AuthorizationManager`.
  74. <6> 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<HttpServletRequest> 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. [[custom-authorization-manager]]
  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. .requestMatchers("/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. ====
  182. Now with the authorization rules applying to all dispatcher types, you have more control of the authorization on them.
  183. For example, you may want to configure `shouldFilterAllDispatcherTypes` to `true` but not apply authorization on requests with dispatcher type `ASYNC` or `FORWARD`.
  184. .Permit ASYNC and FORWARD dispatcher type
  185. ====
  186. .Java
  187. [source,java,role="primary"]
  188. ----
  189. @Bean
  190. SecurityFilterChain web(HttpSecurity http) throws Exception {
  191. http
  192. .authorizeHttpRequests((authorize) -> authorize
  193. .shouldFilterAllDispatcherTypes(true)
  194. .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.FORWARD).permitAll()
  195. .anyRequest().authenticated()
  196. )
  197. // ...
  198. return http.build();
  199. }
  200. ----
  201. .Kotlin
  202. [source,kotlin,role="secondary"]
  203. ----
  204. @Bean
  205. open fun web(http: HttpSecurity): SecurityFilterChain {
  206. http {
  207. authorizeHttpRequests {
  208. shouldFilterAllDispatcherTypes = true
  209. authorize(DispatcherTypeRequestMatcher(DispatcherType.ASYNC, DispatcherType.FORWARD), permitAll)
  210. authorize(anyRequest, authenticated)
  211. }
  212. }
  213. return http.build()
  214. }
  215. ----
  216. ====
  217. You can also customize it to require a specific role for a dispatcher type:
  218. .Require ADMIN for Dispatcher Type ERROR
  219. ====
  220. .Java
  221. [source,java,role="primary"]
  222. ----
  223. @Bean
  224. SecurityFilterChain web(HttpSecurity http) throws Exception {
  225. http
  226. .authorizeHttpRequests((authorize) -> authorize
  227. .shouldFilterAllDispatcherTypes(true)
  228. .dispatcherTypeMatchers(DispatcherType.ERROR).hasRole("ADMIN")
  229. .anyRequest().authenticated()
  230. )
  231. // ...
  232. return http.build();
  233. }
  234. ----
  235. .Kotlin
  236. [source,kotlin,role="secondary"]
  237. ----
  238. @Bean
  239. open fun web(http: HttpSecurity): SecurityFilterChain {
  240. http {
  241. authorizeHttpRequests {
  242. shouldFilterAllDispatcherTypes = true
  243. authorize(DispatcherTypeRequestMatcher(DispatcherType.ERROR), hasRole("ADMIN"))
  244. authorize(anyRequest, authenticated)
  245. }
  246. }
  247. return http.build()
  248. }
  249. ----
  250. ====
  251. == Request Matchers
  252. The `RequestMatcher` interface is used to determine if a request matches a given rule.
  253. We use `securityMatchers` to determine if a given `HttpSecurity` should be applied to a given request.
  254. The same way, we can use `requestMatchers` to determine the authorization rules that we should apply to a given request.
  255. Look at the following example:
  256. ====
  257. .Java
  258. [source,java,role="primary"]
  259. ----
  260. @Configuration
  261. @EnableWebSecurity
  262. public class SecurityConfig {
  263. @Bean
  264. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  265. http
  266. .securityMatcher("/api/**") <1>
  267. .authorizeHttpRequests(authorize -> authorize
  268. .requestMatchers("/user/**").hasRole("USER") <2>
  269. .requestMatchers("/admin/**").hasRole("ADMIN") <3>
  270. .anyRequest().authenticated() <4>
  271. )
  272. .formLogin(withDefaults());
  273. return http.build();
  274. }
  275. }
  276. ----
  277. .Kotlin
  278. [source,kotlin,role="secondary"]
  279. ----
  280. @Configuration
  281. @EnableWebSecurity
  282. open class SecurityConfig {
  283. @Bean
  284. open fun web(http: HttpSecurity): SecurityFilterChain {
  285. http {
  286. securityMatcher("/api/**") <1>
  287. authorizeHttpRequests {
  288. authorize("/user/**", hasRole("USER")) <2>
  289. authorize("/admin/**", hasRole("ADMIN")) <3>
  290. authorize(anyRequest, authenticated) <4>
  291. }
  292. }
  293. return http.build()
  294. }
  295. }
  296. ----
  297. ====
  298. <1> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`
  299. <2> Allow access to URLs that start with `/user/` to users with the `USER` role
  300. <3> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role
  301. <4> Any other request that doesn't match the rules above, will require authentication
  302. 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.
  303. You can read more about the Spring MVC integration xref:servlet/integrations/mvc.adoc[here].
  304. If you want to use a specific `RequestMatcher`, just pass an implementation to the `securityMatcher` and/or `requestMatcher` methods:
  305. ====
  306. .Java
  307. [source,java,role="primary"]
  308. ----
  309. import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; <1>
  310. import static org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher;
  311. @Configuration
  312. @EnableWebSecurity
  313. public class SecurityConfig {
  314. @Bean
  315. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  316. http
  317. .securityMatcher(antMatcher("/api/**")) <2>
  318. .authorizeHttpRequests(authorize -> authorize
  319. .requestMatchers(antMatcher("/user/**")).hasRole("USER") <3>
  320. .requestMatchers(regexMatcher("/admin/.*")).hasRole("ADMIN") <4>
  321. .requestMatchers(new MyCustomRequestMatcher()).hasRole("SUPERVISOR") <5>
  322. .anyRequest().authenticated()
  323. )
  324. .formLogin(withDefaults());
  325. return http.build();
  326. }
  327. }
  328. public class MyCustomRequestMatcher implements RequestMatcher {
  329. @Override
  330. public boolean matches(HttpServletRequest request) {
  331. // ...
  332. }
  333. }
  334. ----
  335. .Kotlin
  336. [source,kotlin,role="secondary"]
  337. ----
  338. import org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher <1>
  339. import org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher
  340. @Configuration
  341. @EnableWebSecurity
  342. open class SecurityConfig {
  343. @Bean
  344. open fun web(http: HttpSecurity): SecurityFilterChain {
  345. http {
  346. securityMatcher(antMatcher("/api/**")) <2>
  347. authorizeHttpRequests {
  348. authorize(antMatcher("/user/**"), hasRole("USER")) <3>
  349. authorize(regexMatcher("/admin/**"), hasRole("ADMIN")) <4>
  350. authorize(MyCustomRequestMatcher(), hasRole("SUPERVISOR")) <5>
  351. authorize(anyRequest, authenticated)
  352. }
  353. }
  354. return http.build()
  355. }
  356. }
  357. ----
  358. ====
  359. <1> Import the static factory methods from `AntPathRequestMatcher` and `RegexRequestMatcher` to create `RequestMatcher` instances.
  360. <2> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`, using `AntPathRequestMatcher`
  361. <3> Allow access to URLs that start with `/user/` to users with the `USER` role, using `AntPathRequestMatcher`
  362. <4> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role, using `RegexRequestMatcher`
  363. <5> Allow access to URLs that match the `MyCustomRequestMatcher` to users with the `SUPERVISOR` role, using a custom `RequestMatcher`
  364. == Expressions
  365. It is recommended that you use type-safe authorization managers instead of SpEL.
  366. However, `WebExpressionAuthorizationManager` is available to help migrate legacy SpEL.
  367. To use `WebExpressionAuthorizationManager`, you can construct one with the expression you are trying to migrate, like so:
  368. ====
  369. .Java
  370. [source,java,role="primary"]
  371. ----
  372. .requestMatchers("/test/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
  373. ----
  374. .Kotlin
  375. [source,kotlin,role="secondary"]
  376. ----
  377. .requestMatchers("/test/**").access(WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
  378. ----
  379. ====
  380. If you are referring to a bean in your expression like so: `@webSecurity.check(authentication, request)`, it's recommended that you instead call the bean directly, which will look something like the following:
  381. ====
  382. .Java
  383. [source,java,role="primary"]
  384. ----
  385. .requestMatchers("/test/**").access((authentication, context) ->
  386. new AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
  387. ----
  388. .Kotlin
  389. [source,kotlin,role="secondary"]
  390. ----
  391. .requestMatchers("/test/**").access((authentication, context): AuthorizationManager<RequestAuthorizationContext> ->
  392. AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
  393. ----
  394. ====
  395. For complex instructions that include bean references as well as other expressions, it is recommended that you change those to implement `AuthorizationManager` and refer to them by calling `.access(AuthorizationManager)`.
  396. If you are not able to do that, you can configure a `DefaultHttpSecurityExpressionHandler` with a bean resolver and supply that to `WebExpressionAuthorizationManager#setExpressionhandler`.