2
0

authorize-http-requests.adoc 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. [[servlet-authorization-authorizationfilter]]
  2. = Authorize HttpServletRequests
  3. :figures: servlet/authorization
  4. Spring Security allows you to xref:servlet/authorization/index.adoc[model your authorization] at the request level.
  5. For example, with Spring Security you can say that all pages under `/admin` require one authority while all other pages simply require authentication.
  6. By default, Spring Security requires that every request be authenticated.
  7. That said, any time you use xref:servlet/configuration/java.adoc#jc-httpsecurity[an `HttpSecurity` instance], it's necessary to declare your authorization rules.
  8. [[activate-request-security]]
  9. Whenever you have an `HttpSecurity` instance, you should at least do:
  10. .Use authorizeHttpRequests
  11. ====
  12. .Java
  13. [source,java,role="primary"]
  14. ----
  15. http
  16. .authorizeHttpRequests((authorize) -> authorize
  17. .anyRequest().authenticated()
  18. )
  19. ----
  20. .Kotlin
  21. [source,kotlin,role="secondary"]
  22. ----
  23. http {
  24. authorizeHttpRequests {
  25. authorize(anyRequest, authenticated)
  26. }
  27. }
  28. ----
  29. .Xml
  30. [source,xml,role="secondary"]
  31. ----
  32. <http>
  33. <intercept-url pattern="/**" access="authenticated"/>
  34. </http>
  35. ----
  36. ====
  37. This tells Spring Security that any endpoint in your application requires that the security context at a minimum be authenticated in order to allow it.
  38. In many cases, your authorization rules will be more sophisticated than that, so please consider the following use cases:
  39. * I have an app that uses `authorizeRequests` and I want to <<migrate-authorize-requests,migrate it to `authorizeHttpRequests`>>
  40. * I want to <<request-authorization-architecture,understand how the `AuthorizationFilter` components work>>
  41. * I want to <<match-requests, match requests>> based on a pattern; specifically <<match-by-regex,regex>>
  42. * I want to <<authorize-requests, authorize requests>>
  43. * I want to <<match-by-custom, match a request programmatically>>
  44. * I want to <<authorize-requests, authorize a request programmatically>>
  45. * I want to <<remote-authorization-manager, delegate request authorization>> to a policy agent
  46. [[request-authorization-architecture]]
  47. == Understanding How Request Authorization Components Work
  48. [NOTE]
  49. 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 at the request level in Servlet-based applications.
  50. .Authorize HttpServletRequest
  51. image::{figures}/authorizationfilter.png[]
  52. * image:{icondir}/number_1.png[] First, the `AuthorizationFilter` constructs a `Supplier` that retrieves an xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder].
  53. * image:{icondir}/number_2.png[] Second, it passes the `Supplier<Authentication>` and the `HttpServletRequest` to the xref:servlet/architecture.adoc#authz-authorization-manager[`AuthorizationManager`].
  54. The `AuthorizationManager` matches the request to the patterns in `authorizeHttpRequests`, and runs the corresponding rule.
  55. ** image:{icondir}/number_3.png[] If authorization is denied, xref:servlet/authorization/events.adoc[an `AuthorizationDeniedEvent` is published], and an `AccessDeniedException` is thrown.
  56. In this case the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`.
  57. ** image:{icondir}/number_4.png[] If access is granted, xref:servlet/authorization/events.adoc[an `AuthorizationGrantedEvent` is published] and `AuthorizationFilter` continues with the xref:servlet/architecture.adoc#servlet-filters-review[FilterChain] which allows the application to process normally.
  58. === `AuthorizationFilter` Is Last By Default
  59. The `AuthorizationFilter` is last in xref:servlet/architecture.adoc#servlet-filterchain-figure[the Spring Security filter chain] by default.
  60. This means that Spring Security's xref:servlet/authentication/index.adoc[authentication filters], xref:servlet/exploits/index.adoc[exploit protections], and other filter integrations do not require authorization.
  61. If you add filters of your own before the `AuthorizationFilter`, they will also not require authorization; otherwise, they will.
  62. A place where this typically becomes important is when you are adding {spring-framework-reference-url}web.html#spring-web[Spring MVC] endpoints.
  63. Because they are executed by the {spring-framework-reference-url}web.html#mvc-servlet[`DispatcherServlet`] and this comes after the `AuthorizationFilter`, you're endpoints need to be <<authorizing-endpoints,included in `authorizeHttpRequests` to be permitted>>.
  64. === All Dispatches Are Authorized
  65. The `AuthorizationFilter` runs not just on every request, but on every dispatch.
  66. This means that the `REQUEST` dispatch needs authorization, but also ``FORWARD``s, ``ERROR``s, and ``INCLUDE``s.
  67. For example, {spring-framework-reference-url}web.html#spring-web[Spring MVC] can `FORWARD` the request to a view resolver that renders a Thymeleaf template, like so:
  68. .Sample Forwarding Spring MVC Controller
  69. ====
  70. .Java
  71. [source,java,role="primary"]
  72. ----
  73. @Controller
  74. public class MyController {
  75. @GetMapping("/endpoint")
  76. public String endpoint() {
  77. return "endpoint";
  78. }
  79. }
  80. ----
  81. .Kotlin
  82. [source,kotlin,role="secondary"]
  83. ----
  84. @Controller
  85. class MyController {
  86. @GetMapping("/endpoint")
  87. fun endpoint(): String {
  88. return "endpoint"
  89. }
  90. }
  91. ----
  92. ====
  93. In this case, authorization happens twice; once for authorizing `/endpoint` and once for forwarding to Thymeleaf to render the "endpoint" template.
  94. For that reason, you may want to <<match-by-dispatcher-type, permit all `FORWARD` dispatches>>.
  95. Another example of this principle is {spring-boot-reference-url}web.html#web.servlet.spring-mvc.error-handling[how Spring Boot handles errors].
  96. If the container catches an exception, say like the following:
  97. .Sample Erroring Spring MVC Controller
  98. ====
  99. .Java
  100. [source,java,role="primary"]
  101. ----
  102. @Controller
  103. public class MyController {
  104. @GetMapping("/endpoint")
  105. public String endpoint() {
  106. throw new UnsupportedOperationException("unsupported");
  107. }
  108. }
  109. ----
  110. .Kotlin
  111. [source,kotlin,role="secondary"]
  112. ----
  113. @Controller
  114. class MyController {
  115. @GetMapping("/endpoint")
  116. fun endpoint(): String {
  117. throw UnsupportedOperationException("unsupported")
  118. }
  119. }
  120. ----
  121. ====
  122. then Boot will dispatch it to the `ERROR` dispatch.
  123. In that case, authorization also happens twice; once for authorizing `/endpoint` and once for dispatching the error.
  124. For that reason, you may want to <<match-by-dispatcher-type, permit all `ERROR` dispatches>>.
  125. === `Authentication` Lookup is Deferred
  126. Remember that xref:servlet/authorization/architecture.adoc#_the_authorizationmanager[the `AuthorizationManager` API uses a `Supplier<Authentication>`].
  127. This matters with `authorizeHttpRequests` when requests are <<authorize-requests,always permitted or always denied>>.
  128. In those cases, xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[the `Authentication`] is not queried, making for a faster request.
  129. [[authorizing-endpoints]]
  130. == Authorizing an Endpoint
  131. You can configure Spring Security to have different rules by adding more rules in order of precedence.
  132. If you want to require that `/endpoint` only be accessible by end users with the `USER` authority, then you can do:
  133. .Authorize an Endpoint
  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. .requestMatchers("/endpoint").hasAuthority('USER')
  143. .anyRequest().authenticated()
  144. )
  145. // ...
  146. return http.build();
  147. }
  148. ----
  149. .Kotlin
  150. [source,kotlin,role="secondary"]
  151. ----
  152. @Bean
  153. SecurityFilterChain web(HttpSecurity http) throws Exception {
  154. http {
  155. authorizeHttpRequests {
  156. authorize("/endpoint", hasAuthority('USER'))
  157. authorize(anyRequest, authenticated)
  158. }
  159. }
  160. return http.build();
  161. }
  162. ----
  163. .Xml
  164. [source,xml,role="secondary"]
  165. ----
  166. <http>
  167. <intercept-url pattern="/endpoint" access="hasAuthority('USER')"/>
  168. <intercept-url pattern="/**" access="authenticated"/>
  169. </http>
  170. ----
  171. ====
  172. As you can see, the declaration can be broken up in to pattern/rule pairs.
  173. `AuthorizationFilter` processes these pairs in the order listed, applying only the first match to the request.
  174. This means that even though `/**` would also match for `/endpoint` the above rules are not a problem.
  175. The way to read the above rules is "if the request is `/endpoint`, then require the `USER` authority; else, only require authentication".
  176. Spring Security supports several patterns and several rules; you can also programmatically create your own of each.
  177. Once authorized, you can test it using xref:servlet/test/method.adoc#test-method-withmockuser[Security's test support] in the following way:
  178. .Test Endpoint Authorization
  179. ====
  180. .Java
  181. [source,java,role="primary"]
  182. ----
  183. @WithMockUser(authorities="USER")
  184. @Test
  185. void endpointWhenUserAuthorityThenAuthorized() {
  186. this.mvc.perform(get("/endpoint"))
  187. .andExpect(status().isOk());
  188. }
  189. @WithMockUser
  190. @Test
  191. void endpointWhenNotUserAuthorityThenForbidden() {
  192. this.mvc.perform(get("/endpoint"))
  193. .andExpect(status().isForbidden());
  194. }
  195. @Test
  196. void anyWhenUnauthenticatedThenUnauthorized() {
  197. this.mvc.perform(get("/any"))
  198. .andExpect(status().isUnauthorized())
  199. }
  200. ----
  201. ====
  202. [[match-requests]]
  203. == Matching Requests
  204. Above you've already seen <<authorizing-endpoints, two ways to match requests>>.
  205. The first you saw was the simplest, which is to match any request.
  206. The second is to match by a URI pattern.
  207. Spring Security supports two languages for URI pattern-matching: <<match-by-ant,Ant>> (as seen above) and <<match-by-regex,Regular Expressions>>.
  208. [[match-by-ant]]
  209. === Matching Using Ant
  210. Ant is the default language that Spring Security uses to match requests.
  211. You can use it to match a single endpoint or a directory, and you can even capture placeholders for later use.
  212. You can also refine it to match a specific set of HTTP methods.
  213. Let's say that you instead of wanting to match the `/endpoint` endpoint, you want to match all endpoints under the `/resource` directory.
  214. In that case, you can do something like the following:
  215. .Match with Ant
  216. ====
  217. .Java
  218. [source,java,role="primary"]
  219. ----
  220. http
  221. .authorizeHttpRequests((authorize) -> authorize
  222. .requestMatchers("/resource/**").hasAuthority("USER")
  223. .anyRequest().authenticated()
  224. )
  225. ----
  226. .Kotlin
  227. [source,kotlin,role="secondary"]
  228. ----
  229. http {
  230. authorizeHttpRequests {
  231. authorize("/resource/**", hasAuthority("USER"))
  232. authorize(anyRequest, authenticated)
  233. }
  234. }
  235. ----
  236. .Xml
  237. [source,xml,role="secondary"]
  238. ----
  239. <http>
  240. <intercept-url pattern="/resource/**" access="hasAuthority('USER')"/>
  241. <intercept-url pattern="/**" access="authenticated"/>
  242. </http>
  243. ----
  244. ====
  245. The way to read this is "if the request is `/resource` or some subdirectory, require the `USER` authority; otherwise, only require authentication"
  246. You can also extract path values from the request, as seen below:
  247. .Authorize and Extract
  248. ====
  249. .Java
  250. [source,java,role="primary"]
  251. ----
  252. http
  253. .authorizeHttpRequests((authorize) -> authorize
  254. .requestMatchers("/resource/{name}").access(new WebExpressionAuthorizationManager("#name == authentication.name"))
  255. .anyRequest().authenticated()
  256. )
  257. ----
  258. .Kotlin
  259. [source,kotlin,role="secondary"]
  260. ----
  261. http {
  262. authorizeHttpRequests {
  263. authorize("/resource/{name}", WebExpressionAuthorizationManager("#name == authentication.name"))
  264. authorize(anyRequest, authenticated)
  265. }
  266. }
  267. ----
  268. .Xml
  269. [source,xml,role="secondary"]
  270. ----
  271. <http>
  272. <intercept-url pattern="/resource/{name}" access="#name == authentication.name"/>
  273. <intercept-url pattern="/**" access="authenticated"/>
  274. </http>
  275. ----
  276. ====
  277. Once authorized, you can test it using xref:servlet/test/method.adoc#test-method-withmockuser[Security's test support] in the following way:
  278. .Test Directory Authorization
  279. ====
  280. .Java
  281. [source,java,role="primary"]
  282. ----
  283. @WithMockUser(authorities="USER")
  284. @Test
  285. void endpointWhenUserAuthorityThenAuthorized() {
  286. this.mvc.perform(get("/endpoint/jon"))
  287. .andExpect(status().isOk());
  288. }
  289. @WithMockUser
  290. @Test
  291. void endpointWhenNotUserAuthorityThenForbidden() {
  292. this.mvc.perform(get("/endpoint/jon"))
  293. .andExpect(status().isForbidden());
  294. }
  295. @Test
  296. void anyWhenUnauthenticatedThenUnauthorized() {
  297. this.mvc.perform(get("/any"))
  298. .andExpect(status().isUnauthorized())
  299. }
  300. ----
  301. ====
  302. [NOTE]
  303. Spring Security only matches paths.
  304. If you want to match query parameters, you will need a custom request matcher.
  305. [[match-by-regex]]
  306. === Matching Using Regular Expressions
  307. Spring Security supports matching requests against a regular expression.
  308. This can come in handy if you want to apply more strict matching criteria than `**` on a subdirectory.
  309. For example, consider a path that contains the username and the rule that all usernames must be alphanumeric.
  310. You can use {security-api-url}org/springframework/security/web/util/matcher/RegexRequestMatcher.html[`RegexRequestMatcher`] to respect this rule, like so:
  311. .Match with Regex
  312. ====
  313. .Java
  314. [source,java,role="primary"]
  315. ----
  316. http
  317. .authorizeHttpRequests((authorize) -> authorize
  318. .requestMatchers(RegexRequestMatcher.regexMatcher("/resource/[A-Za-z0-9]+")).hasAuthority("USER")
  319. .anyRequest().denyAll()
  320. )
  321. ----
  322. .Kotlin
  323. [source,kotlin,role="secondary"]
  324. ----
  325. http {
  326. authorizeHttpRequests {
  327. authorize(RegexRequestMatcher.regexMatcher("/resource/[A-Za-z0-9]+"), hasAuthority("USER"))
  328. authorize(anyRequest, denyAll)
  329. }
  330. }
  331. ----
  332. .Xml
  333. [source,xml,role="secondary"]
  334. ----
  335. <http>
  336. <intercept-url request-matcher="regex" pattern="/resource/[A-Za-z0-9]+" access="hasAuthority('USER')"/>
  337. <intercept-url pattern="/**" access="denyAll"/>
  338. </http>
  339. ----
  340. ====
  341. [[match-by-httpmethod]]
  342. === Matching By Http Method
  343. You can also match rules by HTTP method.
  344. One place where this is handy is when authorizing by permissions granted, like being granted a `read` or `write` privilege.
  345. To require all ``GET``s to have the `read` permission and all ``POST``s to have the `write` permission, you can do something like this:
  346. .Match by HTTP Method
  347. ====
  348. .Java
  349. [source,java,role="primary"]
  350. ----
  351. http
  352. .authorizeHttpRequests((authorize) -> authorize
  353. .requestMatchers(HttpMethod.GET).hasAuthority("read")
  354. .requestMatchers(HttpMethod.POST).hasAuthority("write")
  355. .anyRequest().denyAll()
  356. )
  357. ----
  358. .Kotlin
  359. [source,kotlin,role="secondary"]
  360. ----
  361. http {
  362. authorizeHttpRequests {
  363. authorize(HttpMethod.GET, hasAuthority("read"))
  364. authorize(HttpMethod.POST, hasAuthority("write"))
  365. authorize(anyRequest, denyAll)
  366. }
  367. }
  368. ----
  369. .Xml
  370. [source,xml,role="secondary"]
  371. ----
  372. <http>
  373. <intercept-url http-method="GET" pattern="/**" access="hasAuthority('read')"/>
  374. <intercept-url http-method="POST" pattern="/**" access="hasAuthority('write')"/>
  375. <intercept-url pattern="/**" access="denyAll"/>
  376. </http>
  377. ----
  378. ====
  379. These authorization rules should read as: "if the request is a GET, then require `read` permission; else, if the request is a POST, then require `write` permission; else, deny the request"
  380. [TIP]
  381. Denying the request by default is a healthy security practice since it turns the set of rules into an allow list.
  382. Once authorized, you can test it using xref:servlet/test/method.adoc#test-method-withmockuser[Security's test support] in the following way:
  383. .Test Http Method Authorization
  384. ====
  385. .Java
  386. [source,java,role="primary"]
  387. ----
  388. @WithMockUser(authorities="read")
  389. @Test
  390. void getWhenReadAuthorityThenAuthorized() {
  391. this.mvc.perform(get("/any"))
  392. .andExpect(status().isOk());
  393. }
  394. @WithMockUser
  395. @Test
  396. void getWhenNoReadAuthorityThenForbidden() {
  397. this.mvc.perform(get("/any"))
  398. .andExpect(status().isForbidden());
  399. }
  400. @WithMockUser(authorities="write")
  401. @Test
  402. void postWhenWriteAuthorityThenAuthorized() {
  403. this.mvc.perform(post("/any").with(csrf()))
  404. .andExpect(status().isOk())
  405. }
  406. @WithMockUser(authorities="read")
  407. @Test
  408. void postWhenNoWriteAuthorityThenForbidden() {
  409. this.mvc.perform(get("/any").with(csrf()))
  410. .andExpect(status().isForbidden());
  411. }
  412. ----
  413. ====
  414. [[match-by-dispatcher-type]]
  415. === Matching By Dispatcher Type
  416. [NOTE]
  417. This feature is not currently supported in XML
  418. As stated earlier, Spring Security <<_all_dispatches_are_authorized, authorizes all dispatcher types by default>>.
  419. And even though xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontext[the security context] established on the `REQUEST` dispatch carries over to subsequent dispatches, subtle mismatches can sometimes cause an unexpected `AccessDeniedException`.
  420. To address that, you can configure Spring Security Java configuration to allow dispatcher types like `FORWARD` and `ERROR`, like so:
  421. .Match by Dispatcher Type
  422. ====
  423. .Java
  424. [source,java,role="secondary"]
  425. ----
  426. http
  427. .authorizeHttpRequests((authorize) -> authorize
  428. .dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
  429. .requestMatchers("/endpoint").permitAll()
  430. .anyRequest().denyAll()
  431. )
  432. ----
  433. .Kotlin
  434. [source,kotlin,role="secondary"]
  435. ----
  436. http {
  437. authorizeHttpRequests {
  438. authorize(DispatcherType.FORWARD, permitAll)
  439. authorize(DispatcherType.ERROR, permitAll)
  440. authorize("/endpoint", permitAll)
  441. authorize(anyRequest, denyAll)
  442. }
  443. }
  444. ----
  445. ====
  446. [[match-by-custom]]
  447. === Using a Custom Matcher
  448. [NOTE]
  449. This feature is not currently supported in XML
  450. In Java configuration, you can create your own {security-api-url}org/springframework/security/web/util/matcher/RequestMatcher.html[`RequestMatcher`] and supply it to the DSL like so:
  451. .Authorize by Dispatcher Type
  452. ====
  453. .Java
  454. [source,java,role="secondary"]
  455. ----
  456. RequestMatcher printview = (request) -> request.getParameter("print") != null;
  457. http
  458. .authorizeHttpRequests((authorize) -> authorize
  459. .requestMatchers(printview).hasAuthority("print")
  460. .anyRequest().authenticated()
  461. )
  462. ----
  463. .Kotlin
  464. [source,kotlin,role="secondary"]
  465. ----
  466. val printview: RequestMatcher = { (request) -> request.getParameter("print") != null }
  467. http {
  468. authorizeHttpRequests {
  469. authorize(printview, hasAuthority("print"))
  470. authorize(anyRequest, authenticated)
  471. }
  472. }
  473. ----
  474. ====
  475. [TIP]
  476. Because {security-api-url}org/springframework/security/web/util/matcher/RequestMatcher.html[`RequestMatcher`] is a functional interface, you can supply it as a lambda in the DSL.
  477. However, if you want to extract values from the request, you will need to have a concrete class since that requires overriding a `default` method.
  478. Once authorized, you can test it using xref:servlet/test/method.adoc#test-method-withmockuser[Security's test support] in the following way:
  479. .Test Custom Authorization
  480. ====
  481. .Java
  482. [source,java,role="primary"]
  483. ----
  484. @WithMockUser(authorities="print")
  485. @Test
  486. void printWhenPrintAuthorityThenAuthorized() {
  487. this.mvc.perform(get("/any?print"))
  488. .andExpect(status().isOk());
  489. }
  490. @WithMockUser
  491. @Test
  492. void printWhenNoPrintAuthorityThenForbidden() {
  493. this.mvc.perform(get("/any?print"))
  494. .andExpect(status().isForbidden());
  495. }
  496. ----
  497. ====
  498. [[authorize-requests]]
  499. == Authorizing Requests
  500. Once a request is matched, you can authorize it in several ways <<match-requests, already seen>> like `permitAll`, `denyAll`, and `hasAuthority`.
  501. As a quick summary, here are the authorization rules built into the DSL:
  502. * `permitAll` - The request requires no authorization and is a public endpoint; note that in this case, xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[the `Authentication`] is never retrieved from the session
  503. * `denyAll` - The request is not allowed under any circumstances; note that in this case, the `Authentication` is never retrieved from the session
  504. * `hasAuthority` - The request requires that the `Authentication` have xref:servlet/authorization/architecture.adoc#authz-authorities[a `GrantedAuthority`] that matches the given value
  505. * `hasRole` - A shortcut for `hasAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  506. * `hasAnyAuthority` - The request requires that the `Authentication` have a `GrantedAuthority` that matches any of the given values
  507. * `hasAnyRole` - A shortcut for `hasAnyAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  508. * `access` - The request uses this custom `AuthorizationManager` to determine access
  509. Having now learned the patterns, rules, and how they can be paired together, you should be able to understand what is going on in this more complex example:
  510. .Authorize Requests
  511. ====
  512. .Java
  513. [source,java,role="primary"]
  514. ----
  515. import static jakarta.servlet.DispatcherType.*;
  516. import static org.springframework.security.authorization.AuthorizationManagers.allOf;
  517. import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasAuthority;
  518. import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole;
  519. @Bean
  520. SecurityFilterChain web(HttpSecurity http) throws Exception {
  521. http
  522. // ...
  523. .authorizeHttpRequests(authorize -> authorize // <1>
  524. .dispatcherTypeMatchers(FORWARD, ERROR).permitAll() // <2>
  525. .requestMatchers("/static/**", "/signup", "/about").permitAll() // <3>
  526. .requestMatchers("/admin/**").hasRole("ADMIN") // <4>
  527. .requestMatchers("/db/**").access(allOf(hasAuthority('db'), hasRole('ADMIN'))) // <5>
  528. .anyRequest().denyAll() // <6>
  529. );
  530. return http.build();
  531. }
  532. ----
  533. ====
  534. <1> There are multiple authorization rules specified.
  535. Each rule is considered in the order they were declared.
  536. <2> Dispatches `FORWARD` and `ERROR` are permitted to allow {spring-framework-reference-url}web.html#spring-web[Spring MVC] to render views and Spring Boot to render errors
  537. <3> We specified multiple URL patterns that any user can access.
  538. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
  539. <4> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".
  540. You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix.
  541. <5> Any URL that starts with "/db/" requires the user to have both been granted the "db" permission as well as be a "ROLE_ADMIN".
  542. You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix.
  543. <6> Any URL that has not already been matched on is denied access.
  544. This is a good strategy if you do not want to accidentally forget to update your authorization rules.
  545. [[authorization-expressions]]
  546. == Expressing Authorization with SpEL
  547. While using a concrete `AuthorizationManager` is recommended, there are some cases where an expression is necessary, like with `<intercept-url>` or with JSP Taglibs.
  548. For that reason, this section will focus on examples from those domains.
  549. Given that, let's cover Spring Security's Web Security Authorization SpEL API a bit more in depth.
  550. Spring Security encapsulates all of its authorization fields and methods in a set of root objects.
  551. The most generic root object is called `SecurityExpressionRoot` and it forms the basis for `WebSecurityExpressionRoot`.
  552. Spring Security supplies this root object to `StandardEvaluationContext` when preparing to evaluate an authorization expression.
  553. [[using-authorization-expression-fields-and-methods]]
  554. === Using Authorization Expression Fields and Methods
  555. The first thing this provides is an enhanced set of authorization fields and methods to your SpEL expressions.
  556. What follows is a quick overview of the most common methods:
  557. * `permitAll` - The request requires no authorization to be invoked; note that in this case, xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[the `Authentication`] is never retrieved from the session
  558. * `denyAll` - The request is not allowed under any circumstances; note that in this case, the `Authentication` is never retrieved from the session
  559. * `hasAuthority` - The request requires that the `Authentication` have xref:servlet/authorization/architecture.adoc#authz-authorities[a `GrantedAuthority`] that matches the given value
  560. * `hasRole` - A shortcut for `hasAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  561. * `hasAnyAuthority` - The request requires that the `Authentication` have a `GrantedAuthority` that matches any of the given values
  562. * `hasAnyRole` - A shortcut for `hasAnyAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  563. * `hasPermission` - A hook into your `PermissionEvaluator` instance for doing object-level authorization
  564. And here is a brief look at the most common fields:
  565. * `authentication` - The `Authentication` instance associated with this method invocation
  566. * `principal` - The `Authentication#getPrincipal` associated with this method invocation
  567. Having now learned the patterns, rules, and how they can be paired together, you should be able to understand what is going on in this more complex example:
  568. .Authorize Requests Using SpEL
  569. ====
  570. .Xml
  571. [source,java,role="primary"]
  572. ----
  573. <http>
  574. <intercept-url pattern="/static/**" access="permitAll"/> <1>
  575. <intercept-url pattern="/admin/**" access="hasRole('ADMIN')"/> <2>
  576. <intercept-url pattern="/db/**" access="hasAuthority('db') and hasRole('ADMIN')"/> <3>
  577. <intercept-url pattern="/**" access="denyAll"/> <4>
  578. </http>
  579. ----
  580. ====
  581. <1> We specified a URL patters that any user can access.
  582. Specifically, any user can access a request if the URL starts with "/static/".
  583. <2> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".
  584. You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix.
  585. <3> Any URL that starts with "/db/" requires the user to have both been granted the "db" permission as well as be a "ROLE_ADMIN".
  586. You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix.
  587. <4> Any URL that has not already been matched on is denied access.
  588. This is a good strategy if you do not want to accidentally forget to update your authorization rules.
  589. [[using_path_parameters]]
  590. === Using Path Parameters
  591. Additionally, Spring Security provides a mechanism for discovering path parameters so they can also be accessed in the SpEL expression as well.
  592. For example, you can access a path parameter in your SpEL expression in the following way:
  593. .Authorize Request using SpEL path variable
  594. ====
  595. .Xml
  596. [source,xml,role="primary"]
  597. ----
  598. <http>
  599. <intercept-url pattern="/resource/{name}" access="#name == authentication.name"/>
  600. <intercept-url pattern="/**" access="authenticated"/>
  601. </http>
  602. ----
  603. ====
  604. This expression refers to the path variable after `/resource/` and requires that it is equal to `Authentication#getName`.
  605. [[remote-authorization-manager]]
  606. === Use an Authorization Database, Policy Agent, or Other Service
  607. If you want to configure Spring Security to use a separate service for authorization, you can create your own `AuthorizationManager` and match it to `anyRequest`.
  608. First, your `AuthorizationManager` may look something like this:
  609. .Open Policy Agent Authorization Manager
  610. ====
  611. .Java
  612. [source,java,role="primary"]
  613. ----
  614. @Component
  615. public final class OpenPolicyAgentAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
  616. @Override
  617. public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
  618. // make request to Open Policy Agent
  619. }
  620. }
  621. ----
  622. ====
  623. Then, you can wire it into Spring Security in the following way:
  624. .Any Request Goes to Remote Service
  625. ====
  626. .Java
  627. [source,java,role="primary"]
  628. ----
  629. @Bean
  630. SecurityFilterChain web(HttpSecurity http, AuthorizationManager<RequestAuthorizationContext> authz) throws Exception {
  631. http
  632. // ...
  633. .authorizeHttpRequests((authorize) -> authorize
  634. .anyRequest().access(authz)
  635. );
  636. return http.build();
  637. }
  638. ----
  639. ====
  640. [[favor-permitall]]
  641. === Favor `permitAll` over `ignoring`
  642. When you have static resources it can be tempting to configure the filter chain to ignore these values.
  643. A more secure approach is to permit them using `permitAll` like so:
  644. .Permit Static Resources
  645. ====
  646. .Java
  647. [source,java,role="secondary"]
  648. ----
  649. http
  650. .authorizeHttpRequests((authorize) -> authorize
  651. .requestMatchers("/css/**").permitAll()
  652. .anyRequest().authenticated()
  653. )
  654. ----
  655. .Kotlin
  656. [source,kotlin,role="secondary"]
  657. ----
  658. http {
  659. authorizeHttpRequests {
  660. authorize("/css/**", permitAll)
  661. authorize(anyRequest, authenticated)
  662. }
  663. }
  664. ----
  665. ====
  666. It's more secure because even with static resources it's important to write secure headers, which Spring Security cannot do if the request is ignored.
  667. In this past, this came with a performance tradeoff since the session was consulted by Spring Security on every request.
  668. As of Spring Security 6, however, the session is no longer pinged unless required by the authorization rule.
  669. Because the performance impact is now addressed, Spring Security recommends using at least `permitAll` for all requests.
  670. [[migrate-authorize-requests]]
  671. == Migrating from `authorizeRequests`
  672. [NOTE]
  673. `AuthorizationFilter` supersedes {security-api-url}org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html[`FilterSecurityInterceptor`].
  674. To remain backward compatible, `FilterSecurityInterceptor` remains the default.
  675. This section discusses how `AuthorizationFilter` works and how to override the default configuration.
  676. 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.
  677. 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].
  678. You can override the default when you declare a `SecurityFilterChain`.
  679. Instead of using {security-api-url}org/springframework/security/config/annotation/web/builders/HttpSecurity.html#authorizeRequests()[`authorizeRequests`], use `authorizeHttpRequests`, like so:
  680. .Use authorizeHttpRequests
  681. ====
  682. .Java
  683. [source,java,role="primary"]
  684. ----
  685. @Bean
  686. SecurityFilterChain web(HttpSecurity http) throws AuthenticationException {
  687. http
  688. .authorizeHttpRequests((authorize) -> authorize
  689. .anyRequest().authenticated();
  690. )
  691. // ...
  692. return http.build();
  693. }
  694. ----
  695. ====
  696. This improves on `authorizeRequests` in a number of ways:
  697. 1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters.
  698. This simplifies reuse and customization.
  699. 2. Delays `Authentication` lookup.
  700. 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.
  701. 3. Bean-based configuration support.
  702. When `authorizeHttpRequests` is used instead of `authorizeRequests`, then {security-api-url}org/springframework/security/web/access/intercept/AuthorizationFilter.html[`AuthorizationFilter`] is used instead of {security-api-url}org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html[`FilterSecurityInterceptor`].
  703. === Migrating Expressions
  704. Where possible, it is recommended that you use type-safe authorization managers instead of SpEL.
  705. For Java configuration, {security-api-url}org/springframework/security/web/access/expression/WebExpressionAuthorizationManager.html[`WebExpressionAuthorizationManager`] is available to help migrate legacy SpEL.
  706. To use `WebExpressionAuthorizationManager`, you can construct one with the expression you are trying to migrate, like so:
  707. ====
  708. .Java
  709. [source,java,role="primary"]
  710. ----
  711. .requestMatchers("/test/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
  712. ----
  713. .Kotlin
  714. [source,kotlin,role="secondary"]
  715. ----
  716. .requestMatchers("/test/**").access(WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
  717. ----
  718. ====
  719. 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:
  720. ====
  721. .Java
  722. [source,java,role="primary"]
  723. ----
  724. .requestMatchers("/test/**").access((authentication, context) ->
  725. new AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
  726. ----
  727. .Kotlin
  728. [source,kotlin,role="secondary"]
  729. ----
  730. .requestMatchers("/test/**").access((authentication, context): AuthorizationManager<RequestAuthorizationContext> ->
  731. AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
  732. ----
  733. ====
  734. 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)`.
  735. If you are not able to do that, you can configure a {security-api-url}org/springframework/security/web/access/expression/DefaultHttpSecurityExpressionHandler.html[`DefaultHttpSecurityExpressionHandler`] with a bean resolver and supply that to `WebExpressionAuthorizationManager#setExpressionhandler`.
  736. [[security-matchers]]
  737. == Security Matchers
  738. The {security-api-url}org/springframework/security/web/util/matcher/RequestMatcher.html[`RequestMatcher`] interface is used to determine if a request matches a given rule.
  739. We use `securityMatchers` to determine if xref:servlet/configuration/java.adoc#jc-httpsecurity[a given `HttpSecurity`] should be applied to a given request.
  740. The same way, we can use `requestMatchers` to determine the authorization rules that we should apply to a given request.
  741. Look at the following example:
  742. ====
  743. .Java
  744. [source,java,role="primary"]
  745. ----
  746. @Configuration
  747. @EnableWebSecurity
  748. public class SecurityConfig {
  749. @Bean
  750. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  751. http
  752. .securityMatcher("/api/**") <1>
  753. .authorizeHttpRequests(authorize -> authorize
  754. .requestMatchers("/user/**").hasRole("USER") <2>
  755. .requestMatchers("/admin/**").hasRole("ADMIN") <3>
  756. .anyRequest().authenticated() <4>
  757. )
  758. .formLogin(withDefaults());
  759. return http.build();
  760. }
  761. }
  762. ----
  763. .Kotlin
  764. [source,kotlin,role="secondary"]
  765. ----
  766. @Configuration
  767. @EnableWebSecurity
  768. open class SecurityConfig {
  769. @Bean
  770. open fun web(http: HttpSecurity): SecurityFilterChain {
  771. http {
  772. securityMatcher("/api/**") <1>
  773. authorizeHttpRequests {
  774. authorize("/user/**", hasRole("USER")) <2>
  775. authorize("/admin/**", hasRole("ADMIN")) <3>
  776. authorize(anyRequest, authenticated) <4>
  777. }
  778. }
  779. return http.build()
  780. }
  781. }
  782. ----
  783. ====
  784. <1> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`
  785. <2> Allow access to URLs that start with `/user/` to users with the `USER` role
  786. <3> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role
  787. <4> Any other request that doesn't match the rules above, will require authentication
  788. The `securityMatcher(s)` and `requestMatcher(s)` methods will decide which `RequestMatcher` implementation fits best for your application: If {spring-framework-reference-url}web.html#spring-web[Spring MVC] is in the classpath, then {security-api-url}org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.html[`MvcRequestMatcher`] will be used, otherwise, {security-api-url}org/springframework/security/web/servlet/util/matcher/AntPathRequestMatcher.html[`AntPathRequestMatcher`] will be used.
  789. You can read more about the Spring MVC integration xref:servlet/integrations/mvc.adoc[here].
  790. If you want to use a specific `RequestMatcher`, just pass an implementation to the `securityMatcher` and/or `requestMatcher` methods:
  791. ====
  792. .Java
  793. [source,java,role="primary"]
  794. ----
  795. import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; <1>
  796. import static org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher;
  797. @Configuration
  798. @EnableWebSecurity
  799. public class SecurityConfig {
  800. @Bean
  801. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  802. http
  803. .securityMatcher(antMatcher("/api/**")) <2>
  804. .authorizeHttpRequests(authorize -> authorize
  805. .requestMatchers(antMatcher("/user/**")).hasRole("USER") <3>
  806. .requestMatchers(regexMatcher("/admin/.*")).hasRole("ADMIN") <4>
  807. .requestMatchers(new MyCustomRequestMatcher()).hasRole("SUPERVISOR") <5>
  808. .anyRequest().authenticated()
  809. )
  810. .formLogin(withDefaults());
  811. return http.build();
  812. }
  813. }
  814. public class MyCustomRequestMatcher implements RequestMatcher {
  815. @Override
  816. public boolean matches(HttpServletRequest request) {
  817. // ...
  818. }
  819. }
  820. ----
  821. .Kotlin
  822. [source,kotlin,role="secondary"]
  823. ----
  824. import org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher <1>
  825. import org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher
  826. @Configuration
  827. @EnableWebSecurity
  828. open class SecurityConfig {
  829. @Bean
  830. open fun web(http: HttpSecurity): SecurityFilterChain {
  831. http {
  832. securityMatcher(antMatcher("/api/**")) <2>
  833. authorizeHttpRequests {
  834. authorize(antMatcher("/user/**"), hasRole("USER")) <3>
  835. authorize(regexMatcher("/admin/**"), hasRole("ADMIN")) <4>
  836. authorize(MyCustomRequestMatcher(), hasRole("SUPERVISOR")) <5>
  837. authorize(anyRequest, authenticated)
  838. }
  839. }
  840. return http.build()
  841. }
  842. }
  843. ----
  844. ====
  845. <1> Import the static factory methods from `AntPathRequestMatcher` and `RegexRequestMatcher` to create `RequestMatcher` instances.
  846. <2> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`, using `AntPathRequestMatcher`
  847. <3> Allow access to URLs that start with `/user/` to users with the `USER` role, using `AntPathRequestMatcher`
  848. <4> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role, using `RegexRequestMatcher`
  849. <5> Allow access to URLs that match the `MyCustomRequestMatcher` to users with the `SUPERVISOR` role, using a custom `RequestMatcher`
  850. == Further Reading
  851. Now that you have secured your application's requests, consider xref:servlet/authorization/method-security.adoc[securing its methods].
  852. You can also read further on xref:servlet/test/index.adoc[testing your application] or on integrating Spring Security with other aspects of you application like xref:servlet/integrations/data.adoc[the data layer] or xref:servlet/integrations/observability.adoc[tracing and metrics].