authorize-http-requests.adoc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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. [[remote-authorization-manager]]
  546. === Use an Authorization Database, Policy Agent, or Other Service
  547. 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`.
  548. First, your `AuthorizationManager` may look something like this:
  549. .Open Policy Agent Authorization Manager
  550. ====
  551. .Java
  552. [source,java,role="primary"]
  553. ----
  554. @Component
  555. public final class OpenPolicyAgentAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
  556. @Override
  557. public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
  558. // make request to Open Policy Agent
  559. }
  560. }
  561. ----
  562. ====
  563. Then, you can wire it into Spring Security in the following way:
  564. .Any Request Goes to Remote Service
  565. ====
  566. .Java
  567. [source,java,role="primary"]
  568. ----
  569. @Bean
  570. SecurityFilterChain web(HttpSecurity http, AuthorizationManager<RequestAuthorizationContext> authz) throws Exception {
  571. http
  572. // ...
  573. .authorizeHttpRequests((authorize) -> authorize
  574. .anyRequest().access(authz)
  575. );
  576. return http.build();
  577. }
  578. ----
  579. ====
  580. [[favor-permitall]]
  581. === Favor `permitAll` over `ignoring`
  582. When you have static resources it can be tempting to configure the filter chain to ignore these values.
  583. A more secure approach is to permit them using `permitAll` like so:
  584. .Permit Static Resources
  585. ====
  586. .Java
  587. [source,java,role="secondary"]
  588. ----
  589. http
  590. .authorizeHttpRequests((authorize) -> authorize
  591. .requestMatchers("/css/**").permitAll()
  592. .anyRequest().authenticated()
  593. )
  594. ----
  595. .Kotlin
  596. [source,kotlin,role="secondary"]
  597. ----
  598. http {
  599. authorizeHttpRequests {
  600. authorize("/css/**", permitAll)
  601. authorize(anyRequest, authenticated)
  602. }
  603. }
  604. ----
  605. ====
  606. 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.
  607. In this past, this came with a performance tradeoff since the session was consulted by Spring Security on every request.
  608. As of Spring Security 6, however, the session is no longer pinged unless required by the authorization rule.
  609. Because the performance impact is now addressed, Spring Security recommends using at least `permitAll` for all requests.
  610. [[migrate-authorize-requests]]
  611. == Migrating from `authorizeRequests`
  612. [NOTE]
  613. `AuthorizationFilter` supersedes {security-api-url}org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html[`FilterSecurityInterceptor`].
  614. To remain backward compatible, `FilterSecurityInterceptor` remains the default.
  615. This section discusses how `AuthorizationFilter` works and how to override the default configuration.
  616. 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.
  617. 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].
  618. You can override the default when you declare a `SecurityFilterChain`.
  619. Instead of using {security-api-url}org/springframework/security/config/annotation/web/builders/HttpSecurity.html#authorizeRequests()[`authorizeRequests`], use `authorizeHttpRequests`, like so:
  620. .Use authorizeHttpRequests
  621. ====
  622. .Java
  623. [source,java,role="primary"]
  624. ----
  625. @Bean
  626. SecurityFilterChain web(HttpSecurity http) throws AuthenticationException {
  627. http
  628. .authorizeHttpRequests((authorize) -> authorize
  629. .anyRequest().authenticated();
  630. )
  631. // ...
  632. return http.build();
  633. }
  634. ----
  635. ====
  636. This improves on `authorizeRequests` in a number of ways:
  637. 1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters.
  638. This simplifies reuse and customization.
  639. 2. Delays `Authentication` lookup.
  640. 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.
  641. 3. Bean-based configuration support.
  642. 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`].
  643. === Migrating Expressions
  644. Where possible, it is recommended that you use type-safe authorization managers instead of SpEL.
  645. For Java configuration, {security-api-url}org/springframework/security/web/access/expression/WebExpressionAuthorizationManager.html[`WebExpressionAuthorizationManager`] is available to help migrate legacy SpEL.
  646. To use `WebExpressionAuthorizationManager`, you can construct one with the expression you are trying to migrate, like so:
  647. ====
  648. .Java
  649. [source,java,role="primary"]
  650. ----
  651. .requestMatchers("/test/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
  652. ----
  653. .Kotlin
  654. [source,kotlin,role="secondary"]
  655. ----
  656. .requestMatchers("/test/**").access(WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')"))
  657. ----
  658. ====
  659. 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:
  660. ====
  661. .Java
  662. [source,java,role="primary"]
  663. ----
  664. .requestMatchers("/test/**").access((authentication, context) ->
  665. new AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
  666. ----
  667. .Kotlin
  668. [source,kotlin,role="secondary"]
  669. ----
  670. .requestMatchers("/test/**").access((authentication, context): AuthorizationManager<RequestAuthorizationContext> ->
  671. AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest())))
  672. ----
  673. ====
  674. 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)`.
  675. 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`.
  676. [[security-matchers]]
  677. == Security Matchers
  678. 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.
  679. We use `securityMatchers` to determine if xref:servlet/configuration/java.adoc#jc-httpsecurity[a given `HttpSecurity`] should be applied to a given request.
  680. The same way, we can use `requestMatchers` to determine the authorization rules that we should apply to a given request.
  681. Look at the following example:
  682. ====
  683. .Java
  684. [source,java,role="primary"]
  685. ----
  686. @Configuration
  687. @EnableWebSecurity
  688. public class SecurityConfig {
  689. @Bean
  690. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  691. http
  692. .securityMatcher("/api/**") <1>
  693. .authorizeHttpRequests(authorize -> authorize
  694. .requestMatchers("/user/**").hasRole("USER") <2>
  695. .requestMatchers("/admin/**").hasRole("ADMIN") <3>
  696. .anyRequest().authenticated() <4>
  697. )
  698. .formLogin(withDefaults());
  699. return http.build();
  700. }
  701. }
  702. ----
  703. .Kotlin
  704. [source,kotlin,role="secondary"]
  705. ----
  706. @Configuration
  707. @EnableWebSecurity
  708. open class SecurityConfig {
  709. @Bean
  710. open fun web(http: HttpSecurity): SecurityFilterChain {
  711. http {
  712. securityMatcher("/api/**") <1>
  713. authorizeHttpRequests {
  714. authorize("/user/**", hasRole("USER")) <2>
  715. authorize("/admin/**", hasRole("ADMIN")) <3>
  716. authorize(anyRequest, authenticated) <4>
  717. }
  718. }
  719. return http.build()
  720. }
  721. }
  722. ----
  723. ====
  724. <1> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`
  725. <2> Allow access to URLs that start with `/user/` to users with the `USER` role
  726. <3> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role
  727. <4> Any other request that doesn't match the rules above, will require authentication
  728. 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.
  729. You can read more about the Spring MVC integration xref:servlet/integrations/mvc.adoc[here].
  730. If you want to use a specific `RequestMatcher`, just pass an implementation to the `securityMatcher` and/or `requestMatcher` methods:
  731. ====
  732. .Java
  733. [source,java,role="primary"]
  734. ----
  735. import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; <1>
  736. import static org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher;
  737. @Configuration
  738. @EnableWebSecurity
  739. public class SecurityConfig {
  740. @Bean
  741. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  742. http
  743. .securityMatcher(antMatcher("/api/**")) <2>
  744. .authorizeHttpRequests(authorize -> authorize
  745. .requestMatchers(antMatcher("/user/**")).hasRole("USER") <3>
  746. .requestMatchers(regexMatcher("/admin/.*")).hasRole("ADMIN") <4>
  747. .requestMatchers(new MyCustomRequestMatcher()).hasRole("SUPERVISOR") <5>
  748. .anyRequest().authenticated()
  749. )
  750. .formLogin(withDefaults());
  751. return http.build();
  752. }
  753. }
  754. public class MyCustomRequestMatcher implements RequestMatcher {
  755. @Override
  756. public boolean matches(HttpServletRequest request) {
  757. // ...
  758. }
  759. }
  760. ----
  761. .Kotlin
  762. [source,kotlin,role="secondary"]
  763. ----
  764. import org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher <1>
  765. import org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher
  766. @Configuration
  767. @EnableWebSecurity
  768. open class SecurityConfig {
  769. @Bean
  770. open fun web(http: HttpSecurity): SecurityFilterChain {
  771. http {
  772. securityMatcher(antMatcher("/api/**")) <2>
  773. authorizeHttpRequests {
  774. authorize(antMatcher("/user/**"), hasRole("USER")) <3>
  775. authorize(regexMatcher("/admin/**"), hasRole("ADMIN")) <4>
  776. authorize(MyCustomRequestMatcher(), hasRole("SUPERVISOR")) <5>
  777. authorize(anyRequest, authenticated)
  778. }
  779. }
  780. return http.build()
  781. }
  782. }
  783. ----
  784. ====
  785. <1> Import the static factory methods from `AntPathRequestMatcher` and `RegexRequestMatcher` to create `RequestMatcher` instances.
  786. <2> Configure `HttpSecurity` to only be applied to URLs that start with `/api/`, using `AntPathRequestMatcher`
  787. <3> Allow access to URLs that start with `/user/` to users with the `USER` role, using `AntPathRequestMatcher`
  788. <4> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role, using `RegexRequestMatcher`
  789. <5> Allow access to URLs that match the `MyCustomRequestMatcher` to users with the `SUPERVISOR` role, using a custom `RequestMatcher`
  790. == Further Reading
  791. Now that you have secured your application's requests, consider xref:servlet/authorization/method-security.adoc[securing its methods].
  792. 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].