authorize-http-requests.adoc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. [.invert-dark]
  40. image::{figures}/authorizationfilter.png[]
  41. * 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].
  42. It wraps this in an `Supplier` in order to delay lookup.
  43. * image:{icondir}/number_2.png[] Second, it passes the `Supplier<Authentication>` and the `HttpServletRequest` to the xref:servlet/architecture.adoc#authz-authorization-manager[`AuthorizationManager`].
  44. ** image:{icondir}/number_3.png[] If authorization is denied, an `AccessDeniedException` is thrown.
  45. In this case the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`.
  46. ** 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.
  47. We can configure Spring Security to have different rules by adding more rules in order of precedence.
  48. .Authorize Requests
  49. [tabs]
  50. ======
  51. Java::
  52. +
  53. [source,java,role="primary"]
  54. ----
  55. @Bean
  56. SecurityFilterChain web(HttpSecurity http) throws Exception {
  57. http
  58. // ...
  59. .authorizeHttpRequests(authorize -> authorize // <1>
  60. .requestMatchers("/resources/**", "/signup", "/about").permitAll() // <2>
  61. .requestMatchers("/admin/**").hasRole("ADMIN") // <3>
  62. .requestMatchers("/db/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') and hasRole('DBA')")) // <4>
  63. // .requestMatchers("/db/**").access(AuthorizationManagers.allOf(AuthorityAuthorizationManager.hasRole("ADMIN"), AuthorityAuthorizationManager.hasRole("DBA"))) // <5>
  64. .anyRequest().denyAll() // <6>
  65. );
  66. return http.build();
  67. }
  68. ----
  69. ======
  70. <1> There are multiple authorization rules specified.
  71. Each rule is considered in the order they were declared.
  72. <2> We specified multiple URL patterns that any user can access.
  73. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
  74. <3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".
  75. You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix.
  76. <4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA".
  77. You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix.
  78. <5> The same rule from 4, could be written by combining multiple `AuthorizationManager`.
  79. <6> Any URL that has not already been matched on is denied access.
  80. This is a good strategy if you do not want to accidentally forget to update your authorization rules.
  81. You can take a bean-based approach by constructing your own xref:servlet/authorization/architecture.adoc#authz-delegate-authorization-manager[`RequestMatcherDelegatingAuthorizationManager`] like so:
  82. .Configure RequestMatcherDelegatingAuthorizationManager
  83. [tabs]
  84. ======
  85. Java::
  86. +
  87. [source,java,role="primary"]
  88. ----
  89. @Bean
  90. SecurityFilterChain web(HttpSecurity http, AuthorizationManager<RequestAuthorizationContext> access)
  91. throws AuthenticationException {
  92. http
  93. .authorizeHttpRequests((authorize) -> authorize
  94. .anyRequest().access(access)
  95. )
  96. // ...
  97. return http.build();
  98. }
  99. @Bean
  100. AuthorizationManager<RequestAuthorizationContext> requestMatcherAuthorizationManager(HandlerMappingIntrospector introspector) {
  101. MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);
  102. RequestMatcher permitAll =
  103. new AndRequestMatcher(
  104. mvcMatcherBuilder.pattern("/resources/**"),
  105. mvcMatcherBuilder.pattern("/signup"),
  106. mvcMatcherBuilder.pattern("/about"));
  107. RequestMatcher admin = mvcMatcherBuilder.pattern("/admin/**");
  108. RequestMatcher db = mvcMatcherBuilder.pattern("/db/**");
  109. RequestMatcher any = AnyRequestMatcher.INSTANCE;
  110. AuthorizationManager<HttpServletRequest> 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. [[custom-authorization-manager]]
  122. Here is an example of mapping a custom authorization manager to the `my/authorized/endpoint`:
  123. .Custom Authorization Manager
  124. [tabs]
  125. ======
  126. Java::
  127. +
  128. [source,java,role="primary"]
  129. ----
  130. @Bean
  131. SecurityFilterChain web(HttpSecurity http) throws Exception {
  132. http
  133. .authorizeHttpRequests((authorize) -> authorize
  134. .requestMatchers("/my/authorized/endpoint").access(new CustomAuthorizationManager());
  135. )
  136. // ...
  137. return http.build();
  138. }
  139. ----
  140. ======
  141. Or you can provide it for all requests as seen below:
  142. .Custom Authorization Manager for All Requests
  143. [tabs]
  144. ======
  145. Java::
  146. +
  147. [source,java,role="primary"]
  148. ----
  149. @Bean
  150. SecurityFilterChain web(HttpSecurity http) throws Exception {
  151. http
  152. .authorizeHttpRequests((authorize) -> authorize
  153. .anyRequest().access(new CustomAuthorizationManager());
  154. )
  155. // ...
  156. return http.build();
  157. }
  158. ----
  159. ======
  160. By default, the `AuthorizationFilter` does not apply to `DispatcherType.ERROR` and `DispatcherType.ASYNC`.
  161. We can configure Spring Security to apply the authorization rules to all dispatcher types by using the `shouldFilterAllDispatcherTypes` method:
  162. .Set shouldFilterAllDispatcherTypes to true
  163. [tabs]
  164. ======
  165. Java::
  166. +
  167. [source,java,role="primary"]
  168. ----
  169. @Bean
  170. SecurityFilterChain web(HttpSecurity http) throws Exception {
  171. http
  172. .authorizeHttpRequests((authorize) -> authorize
  173. .shouldFilterAllDispatcherTypes(true)
  174. .anyRequest.authenticated()
  175. )
  176. // ...
  177. return http.build();
  178. }
  179. ----
  180. Kotlin::
  181. +
  182. [source,kotlin,role="secondary"]
  183. ----
  184. @Bean
  185. open fun web(http: HttpSecurity): SecurityFilterChain {
  186. http {
  187. authorizeHttpRequests {
  188. shouldFilterAllDispatcherTypes = true
  189. authorize(anyRequest, authenticated)
  190. }
  191. }
  192. return http.build()
  193. }
  194. ----
  195. ======
  196. Now with the authorization rules applying to all dispatcher types, you have more control of the authorization on them.
  197. For example, you may want to configure `shouldFilterAllDispatcherTypes` to `true` but not apply authorization on requests with dispatcher type `ASYNC` or `FORWARD`.
  198. .Permit ASYNC and FORWARD dispatcher type
  199. [tabs]
  200. ======
  201. Java::
  202. +
  203. [source,java,role="primary"]
  204. ----
  205. @Bean
  206. SecurityFilterChain web(HttpSecurity http) throws Exception {
  207. http
  208. .authorizeHttpRequests((authorize) -> authorize
  209. .shouldFilterAllDispatcherTypes(true)
  210. .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.FORWARD).permitAll()
  211. .anyRequest().authenticated()
  212. )
  213. // ...
  214. return http.build();
  215. }
  216. ----
  217. Kotlin::
  218. +
  219. [source,kotlin,role="secondary"]
  220. ----
  221. @Bean
  222. open fun web(http: HttpSecurity): SecurityFilterChain {
  223. http {
  224. authorizeHttpRequests {
  225. shouldFilterAllDispatcherTypes = true
  226. authorize(DispatcherTypeRequestMatcher(DispatcherType.ASYNC, DispatcherType.FORWARD), permitAll)
  227. authorize(anyRequest, authenticated)
  228. }
  229. }
  230. return http.build()
  231. }
  232. ----
  233. ======
  234. You can also customize it to require a specific role for a dispatcher type:
  235. .Require ADMIN for Dispatcher Type ERROR
  236. [tabs]
  237. ======
  238. Java::
  239. +
  240. [source,java,role="primary"]
  241. ----
  242. @Bean
  243. SecurityFilterChain web(HttpSecurity http) throws Exception {
  244. http
  245. .authorizeHttpRequests((authorize) -> authorize
  246. .shouldFilterAllDispatcherTypes(true)
  247. .dispatcherTypeMatchers(DispatcherType.ERROR).hasRole("ADMIN")
  248. .anyRequest().authenticated()
  249. )
  250. // ...
  251. return http.build();
  252. }
  253. ----
  254. Kotlin::
  255. +
  256. [source,kotlin,role="secondary"]
  257. ----
  258. @Bean
  259. open fun web(http: HttpSecurity): SecurityFilterChain {
  260. http {
  261. authorizeHttpRequests {
  262. shouldFilterAllDispatcherTypes = true
  263. authorize(DispatcherTypeRequestMatcher(DispatcherType.ERROR), hasRole("ADMIN"))
  264. authorize(anyRequest, authenticated)
  265. }
  266. }
  267. return http.build()
  268. }
  269. ----
  270. ======
  271. == Request Matchers
  272. The `RequestMatcher` interface is used to determine if a request matches a given rule.
  273. We use `securityMatchers` to determine if a given `HttpSecurity` should be applied to a given request.
  274. The same way, we can use `requestMatchers` to determine the authorization rules that we should apply to a given request.
  275. Look at the following example:
  276. [tabs]
  277. ======
  278. Java::
  279. +
  280. [source,java,role="primary"]
  281. ----
  282. @Configuration
  283. @EnableWebSecurity
  284. public class SecurityConfig {
  285. @Bean
  286. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  287. http
  288. .securityMatcher("/api/**") <1>
  289. .authorizeHttpRequests(authorize -> authorize
  290. .requestMatchers("/user/**").hasRole("USER") <2>
  291. .requestMatchers("/admin/**").hasRole("ADMIN") <3>
  292. .anyRequest().authenticated() <4>
  293. )
  294. .formLogin(withDefaults());
  295. return http.build();
  296. }
  297. }
  298. ----
  299. Kotlin::
  300. +
  301. [source,kotlin,role="secondary"]
  302. ----
  303. @Configuration
  304. @EnableWebSecurity
  305. open class SecurityConfig {
  306. @Bean
  307. open fun web(http: HttpSecurity): SecurityFilterChain {
  308. http {
  309. securityMatcher("/api/**") <1>
  310. authorizeHttpRequests {
  311. authorize("/user/**", hasRole("USER")) <2>
  312. authorize("/admin/**", hasRole("ADMIN")) <3>
  313. authorize(anyRequest, authenticated) <4>
  314. }
  315. }
  316. return http.build()
  317. }
  318. }
  319. ----
  320. ======
  321. <1> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`
  322. <2> Allow access to URLs that start with `/user/` to users with the `USER` role
  323. <3> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role
  324. <4> Any other request that doesn't match the rules above, will require authentication
  325. 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.
  326. You can read more about the Spring MVC integration xref:servlet/integrations/mvc.adoc[here].
  327. If you want to use a specific `RequestMatcher`, just pass an implementation to the `securityMatcher` and/or `requestMatcher` methods:
  328. [tabs]
  329. ======
  330. Java::
  331. +
  332. [source,java,role="primary"]
  333. ----
  334. import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; <1>
  335. import static org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher;
  336. @Configuration
  337. @EnableWebSecurity
  338. public class SecurityConfig {
  339. @Bean
  340. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  341. http
  342. .securityMatcher(antMatcher("/api/**")) <2>
  343. .authorizeHttpRequests(authorize -> authorize
  344. .requestMatchers(antMatcher("/user/**")).hasRole("USER") <3>
  345. .requestMatchers(regexMatcher("/admin/.*")).hasRole("ADMIN") <4>
  346. .requestMatchers(new MyCustomRequestMatcher()).hasRole("SUPERVISOR") <5>
  347. .anyRequest().authenticated()
  348. )
  349. .formLogin(withDefaults());
  350. return http.build();
  351. }
  352. }
  353. public class MyCustomRequestMatcher implements RequestMatcher {
  354. @Override
  355. public boolean matches(HttpServletRequest request) {
  356. // ...
  357. }
  358. }
  359. ----
  360. Kotlin::
  361. +
  362. [source,kotlin,role="secondary"]
  363. ----
  364. import org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher <1>
  365. import org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher
  366. @Configuration
  367. @EnableWebSecurity
  368. open class SecurityConfig {
  369. @Bean
  370. open fun web(http: HttpSecurity): SecurityFilterChain {
  371. http {
  372. securityMatcher(antMatcher("/api/**")) <2>
  373. authorizeHttpRequests {
  374. authorize(antMatcher("/user/**"), hasRole("USER")) <3>
  375. authorize(regexMatcher("/admin/**"), hasRole("ADMIN")) <4>
  376. authorize(MyCustomRequestMatcher(), hasRole("SUPERVISOR")) <5>
  377. authorize(anyRequest, authenticated)
  378. }
  379. }
  380. return http.build()
  381. }
  382. }
  383. ----
  384. ======
  385. <1> Import the static factory methods from `AntPathRequestMatcher` and `RegexRequestMatcher` to create `RequestMatcher` instances.
  386. <2> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`, using `AntPathRequestMatcher`
  387. <3> Allow access to URLs that start with `/user/` to users with the `USER` role, using `AntPathRequestMatcher`
  388. <4> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role, using `RegexRequestMatcher`
  389. <5> Allow access to URLs that match the `MyCustomRequestMatcher` to users with the `SUPERVISOR` role, using a custom `RequestMatcher`
  390. == Expressions
  391. It is recommended that you use type-safe authorization managers instead of SpEL.
  392. However, `WebExpressionAuthorizationManager` is available to help migrate legacy SpEL.
  393. To use `WebExpressionAuthorizationManager`, you can construct one with the expression you are trying to migrate, like so:
  394. [tabs]
  395. ======
  396. Java::
  397. +
  398. [source,java,role="primary"]
  399. ----
  400. .requestMatchers("/test/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
  401. ----
  402. Kotlin::
  403. +
  404. [source,kotlin,role="secondary"]
  405. ----
  406. .requestMatchers("/test/**").access(WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
  407. ----
  408. ======
  409. 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:
  410. [tabs]
  411. ======
  412. Java::
  413. +
  414. [source,java,role="primary"]
  415. ----
  416. .requestMatchers("/test/**").access((authentication, context) ->
  417. new AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
  418. ----
  419. Kotlin::
  420. +
  421. [source,kotlin,role="secondary"]
  422. ----
  423. .requestMatchers("/test/**").access((authentication, context): AuthorizationManager<RequestAuthorizationContext> ->
  424. AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
  425. ----
  426. ======
  427. 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)`.
  428. If you are not able to do that, you can configure a `DefaultHttpSecurityExpressionHandler` with a bean resolver and supply that to `WebExpressionAuthorizationManager#setExpressionhandler`.