authorize-http-requests.adoc 41 KB

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