You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -199,12 +199,16 @@ Note that this configuration is parallels the XML Namespace configuration:
199
199
</http>
200
200
----
201
201
202
-
== Multiple HttpSecurity Instances
202
+
=== Multiple HttpSecurity Instances
203
+
204
+
To effectively manage security in an application where certain areas need different protection, we can employ multiple filter chains alongside the `securityMatcher` DSL method.
205
+
This approach allows us to define distinct security configurations tailored to specific parts of the application, enhancing overall application security and control.
203
206
204
207
We can configure multiple `HttpSecurity` instances just as we can have multiple `<http>` blocks in XML.
205
208
The key is to register multiple `SecurityFilterChain` ``@Bean``s.
206
-
The following example has a different configuration for URLs that start with `/api/`.
209
+
The following example has a different configuration for URLs that begin with `/api/`.
207
210
211
+
[[multiple-httpsecurity-instances-java]]
208
212
[source,java]
209
213
----
210
214
@Configuration
@@ -228,7 +232,7 @@ public class MultiHttpSecurityConfig {
228
232
.authorizeHttpRequests(authorize -> authorize
229
233
.anyRequest().hasRole("ADMIN")
230
234
)
231
-
.httpBasic(withDefaults());
235
+
.httpBasic(Customizer.withDefaults());
232
236
return http.build();
233
237
}
234
238
@@ -238,111 +242,244 @@ public class MultiHttpSecurityConfig {
238
242
.authorizeHttpRequests(authorize -> authorize
239
243
.anyRequest().authenticated()
240
244
)
241
-
.formLogin(withDefaults());
245
+
.formLogin(Customizer.withDefaults());
242
246
return http.build();
243
247
}
244
248
}
245
249
----
246
250
<1> Configure Authentication as usual.
247
251
<2> Create an instance of `SecurityFilterChain` that contains `@Order` to specify which `SecurityFilterChain` should be considered first.
248
-
<3> The `http.securityMatcher` states that this `HttpSecurity` is applicable only to URLs that start with `/api/`.
252
+
<3> The `http.securityMatcher()` states that this `HttpSecurity` is applicable only to URLs that begin with `/api/`.
249
253
<4> Create another instance of `SecurityFilterChain`.
250
-
If the URL does not start with `/api/`, this configuration is used.
254
+
If the URL does not begin with `/api/`, this configuration is used.
251
255
This configuration is considered after `apiFilterChain`, since it has an `@Order` value after `1` (no `@Order` defaults to last).
252
256
253
-
To effectively manage security in an application where certain areas and the entire app need protection, we can employ multiple filter chains alongside the securityMatcher. This approach allows us to define distinct security configurations tailored to specific parts while also ensuring overall application security. The provided example showcases distinct configurations for URLs starting with "/account/", "/balance", "/loans-approval/", "/credit-cards-approval/", "/loans", "/cards", "/notices", "/contact", "/login", "/logout" and "/register". This approach allows tailored security settings for specific endpoints, enhancing overall application security and control.
257
+
=== Choosing `securityMatcher` or `requestMatchers`
258
+
259
+
A common question is:
260
+
261
+
> What is the difference between the `http.securityMatcher()` method and `requestMatchers()` used for request authorization (i.e. inside of `http.authorizeHttpRequests()`)?
262
+
263
+
To answer this question, it helps to understand that each `HttpSecurity` instance used to build a `SecurityFilterChain` contains a `RequestMatcher` to match incoming requests.
264
+
If a request does not match a `SecurityFilterChain` with higher priority (e.g. `@Order(1)`), the request can be tried against a filter chain with lower priority (e.g. no `@Order`).
265
+
266
+
[NOTE]
267
+
====
268
+
The matching logic for multiple filter chains is performed by the xref:servlet/architecture.adoc#servlet-filterchainproxy[`FilterChainProxy`].
269
+
====
270
+
271
+
The default `RequestMatcher` matches *any request* to ensure Spring Security protects *all requests by default*.
272
+
273
+
[NOTE]
274
+
====
275
+
Specifying a `securityMatcher` overrides this default.
276
+
====
277
+
278
+
[WARNING]
279
+
====
280
+
If no filter chain matches a particular request, the request is *not protected* by Spring Security.
281
+
====
282
+
283
+
The following example demonstrates a single filter chain that only protects requests that begin with `/secured/`:
<1> Requests that begin with `/secured/` will be protected but any other requests are not protected.
313
+
<2> Requests to `/secured/user` require the `ROLE_USER` authority.
314
+
<3> Requests to `/secured/admin` require the `ROLE_ADMIN` authority.
315
+
<4> Any other requests (such as `/secured/other`) simply require an authenticated user.
316
+
317
+
[TIP]
318
+
====
319
+
It is _recommended_ to provide a `SecurityFilterChain` that does not specify any `securityMatcher` to ensure the entire application is protected, as demonstrated in the <<multiple-httpsecurity-instances-java,earlier example>>.
320
+
====
321
+
322
+
Notice that the `requestMatchers` method only applies to individual authorization rules.
323
+
Each request listed there must also match the overall `securityMatcher` for this particular `HttpSecurity` instance used to create the `SecurityFilterChain`.
324
+
Using `anyRequest()` in this example matches all other requests within this particular `SecurityFilterChain` (which must begin with `/secured/`).
325
+
326
+
[NOTE]
327
+
====
328
+
See xref:servlet/authorization/authorize-http-requests.adoc[Authorize HttpServletRequests] for more information on `requestMatchers`.
329
+
====
330
+
331
+
=== `SecurityFilterChain` Endpoints
332
+
333
+
Several filters in the `SecurityFilterChain` directly provide endpoints, such as the `UsernamePasswordAuthenticationFilter` which is set up by `http.formLogin()` and provides the `POST /login` endpoint.
334
+
In the <<choosing-security-matcher-request-matchers-java,above example>>, the `/login` endpoint is not matched by `http.securityMatcher("/secured/**")` and therefore that application would not have any `GET /login` or `POST /login` endpoint.
335
+
Such requests would return `404 Not Found`.
336
+
This is often surprising to users.
337
+
338
+
Specifying `http.securityMatcher()` affects what requests are matched by that `SecurityFilterChain`.
339
+
However, it does not automatically affect endpoints provided by the filter chain.
340
+
In such cases, you may need to customize the URL of any endpoints you would like the filter chain to provide.
341
+
342
+
The following example demonstrates a configuration that secures requests that begin with `/secured/` and denies all other requests, while also customizing endpoints provided by the `SecurityFilterChain`:
343
+
344
+
[[security-filter-chain-endpoints-java]]
345
+
[source,java]
346
+
----
347
+
@Configuration
348
+
@EnableWebSecurity
349
+
public class SecuredSecurityConfig {
350
+
351
+
@Bean
352
+
public UserDetailsService userDetailsService() throws Exception {
353
+
// ...
354
+
}
355
+
356
+
@Bean
357
+
@Order(1)
358
+
public SecurityFilterChain securedFilterChain(HttpSecurity http) throws Exception {
359
+
http
360
+
.securityMatcher("/secured/**") <1>
361
+
.authorizeHttpRequests(authorize -> authorize
362
+
.anyRequest().authenticated() <2>
363
+
)
364
+
.formLogin(formLogin -> formLogin <3>
365
+
.loginPage("/secured/login")
366
+
.loginProcessingUrl("/secured/login")
367
+
.permitAll()
368
+
)
369
+
.logout(logout -> logout <4>
370
+
.logoutUrl("/secured/logout")
371
+
.logoutSuccessUrl("/secured/login?logout")
372
+
.permitAll()
373
+
)
374
+
.formLogin(Customizer.withDefaults());
375
+
return http.build();
376
+
}
377
+
378
+
@Bean
379
+
public SecurityFilterChain defaultFilterChain(HttpSecurity http) throws Exception {
380
+
http
381
+
.authorizeHttpRequests(authorize -> authorize
382
+
.anyRequest().denyAll() <5>
383
+
);
384
+
return http.build();
385
+
}
386
+
}
387
+
----
388
+
<1> Requests that begin with `/secured/` will be protected by this filter chain.
389
+
<2> Requests that begin with `/secured/` require an authenticated user.
390
+
<3> Customize form login to prefix URLs with `/secured/`.
391
+
<4> Customize logout to prefix URLs with `/secured/`.
392
+
<5> All other requests will be denied.
393
+
394
+
[NOTE]
395
+
====
396
+
This example customizes the login and logout pages, which disables Spring Security's generated pages.
397
+
You must xref:servlet/authentication/passwords/form.html#servlet-authentication-form-custom[provide your own] custom endpoints for `GET /secured/login` and `GET /secured/logout`.
398
+
Note that Spring Security still provides `POST /secured/login` and `POST /secured/logout` endpoints for you.
399
+
====
400
+
401
+
=== Real World Example
402
+
403
+
The following example demonstrates a slightly more real-world configuration putting all of these elements together:
<2> Define a SecurityFilterChain instance with @Order(1), which means that this chain will have the highest priority.
332
-
<3> Specify that the http.securityMatcher applies only to "/account", "/loans", and "/cards" URLs.
333
-
<4> Requires the user to have the role "USER" to access the URLs "/account", "/loans", and "/cards".
334
-
<5> Next, create another SecurityFilterChain instance with @Order(2), this chain will be considered second.
335
-
<6> Indicate that the http.securityMatcher applies only to "/balance" URL.
336
-
<7> Requires the user to have the role "USER" or the role "ADMIN" to access the URL "/balance"
337
-
<8> Next, create another SecurityFilterChain instance with @Order(3), this particular security filter chain will be the third in the order of execution.
338
-
<9> The http.securityMatcher applies only to "/loans-approval" and "/credit-cards-approval" URLs.
339
-
<10> The user must have the role "ADMIN" to access the URLs "/loans-approval" and "/credit-cards-approval"
340
-
<11> Define a SecurityFilterChain instance with @Order(4) this chain will be considered fourth.
341
-
<12> The http.securityMatcher applies only to "/login", "/logout", "/notices", "/contact", "/register" URLs.
342
-
<13> Allows access to these specific URLs without authentication.
343
-
<14> Lastly, create an additional SecurityFilterChain instance without an @Order annotation. This configuration will handle requests not covered by the other filter chains and will be processed last (no @Order defaults to last).
344
-
<15> Requires the user to be authenticated to access any URL not explicitly allowed or protected by other filter chains.
345
-
471
+
<2> Define a `SecurityFilterChain` instance with `@Order(1)`, which means that this filter chain will have the highest priority.
472
+
This filter chain applies only to requests that begin with `/accounts/approvals/`, `/loans/approvals/` or `/credit-cards/approvals/`.
473
+
Requests to this filter chain require the `ROLE_ADMIN` authority and allow HTTP Basic Authentication.
474
+
<3> Next, create another `SecurityFilterChain` instance with `@Order(2)` which will be considered second.
475
+
This filter chain applies only to requests that begin with `/accounts/`, `/loans/`, `/credit-cards/`, or `/balances/`.
476
+
Notice that because this filter chain is second, any requests that include `/approvals/` will match the previous filter chain and will *not* be matched by this filter chain.
477
+
Requests to this filter chain require the `ROLE_USER` authority.
478
+
This filter chain does not define any authentication because the next (default) filter chain contains that configuration.
479
+
<4> Lastly, create an additional `SecurityFilterChain` instance without an `@Order` annotation.
480
+
This configuration will handle requests not covered by the other filter chains and will be processed last (no `@Order` defaults to last).
481
+
Requests that match `/user-login`, `/user-logout`, `/notices`, `/contact` and `/register` allow access without authentication.
482
+
Any other requests require the user to be authenticated to access any URL not explicitly allowed or protected by other filter chains.
0 commit comments