Polish gh-15029
This commit is contained in:
parent
046a1fc811
commit
2482e8e446
|
@ -176,8 +176,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
|||
.authorizeHttpRequests(authorize -> authorize
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.formLogin(withDefaults())
|
||||
.httpBasic(withDefaults());
|
||||
.formLogin(Customizer.withDefaults())
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
|
@ -199,12 +199,16 @@ Note that this configuration is parallels the XML Namespace configuration:
|
|||
</http>
|
||||
----
|
||||
|
||||
== Multiple HttpSecurity Instances
|
||||
=== Multiple HttpSecurity Instances
|
||||
|
||||
To effectively manage security in an application where certain areas need different protection, we can employ multiple filter chains alongside the `securityMatcher` DSL method.
|
||||
This approach allows us to define distinct security configurations tailored to specific parts of the application, enhancing overall application security and control.
|
||||
|
||||
We can configure multiple `HttpSecurity` instances just as we can have multiple `<http>` blocks in XML.
|
||||
The key is to register multiple `SecurityFilterChain` ``@Bean``s.
|
||||
The following example has a different configuration for URLs that start with `/api/`.
|
||||
The following example has a different configuration for URLs that begin with `/api/`.
|
||||
|
||||
[[multiple-httpsecurity-instances-java]]
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
|
@ -228,7 +232,7 @@ public class MultiHttpSecurityConfig {
|
|||
.authorizeHttpRequests(authorize -> authorize
|
||||
.anyRequest().hasRole("ADMIN")
|
||||
)
|
||||
.httpBasic(withDefaults());
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
|
@ -238,111 +242,244 @@ public class MultiHttpSecurityConfig {
|
|||
.authorizeHttpRequests(authorize -> authorize
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.formLogin(withDefaults());
|
||||
.formLogin(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Configure Authentication as usual.
|
||||
<2> Create an instance of `SecurityFilterChain` that contains `@Order` to specify which `SecurityFilterChain` should be considered first.
|
||||
<3> The `http.securityMatcher` states that this `HttpSecurity` is applicable only to URLs that start with `/api/`.
|
||||
<3> The `http.securityMatcher()` states that this `HttpSecurity` is applicable only to URLs that begin with `/api/`.
|
||||
<4> Create another instance of `SecurityFilterChain`.
|
||||
If the URL does not start with `/api/`, this configuration is used.
|
||||
If the URL does not begin with `/api/`, this configuration is used.
|
||||
This configuration is considered after `apiFilterChain`, since it has an `@Order` value after `1` (no `@Order` defaults to last).
|
||||
|
||||
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.
|
||||
=== Choosing `securityMatcher` or `requestMatchers`
|
||||
|
||||
A common question is:
|
||||
|
||||
> What is the difference between the `http.securityMatcher()` method and `requestMatchers()` used for request authorization (i.e. inside of `http.authorizeHttpRequests()`)?
|
||||
|
||||
To answer this question, it helps to understand that each `HttpSecurity` instance used to build a `SecurityFilterChain` contains a `RequestMatcher` to match incoming requests.
|
||||
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`).
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
The matching logic for multiple filter chains is performed by the xref:servlet/architecture.adoc#servlet-filterchainproxy[`FilterChainProxy`].
|
||||
====
|
||||
|
||||
The default `RequestMatcher` matches *any request* to ensure Spring Security protects *all requests by default*.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
Specifying a `securityMatcher` overrides this default.
|
||||
====
|
||||
|
||||
[WARNING]
|
||||
====
|
||||
If no filter chain matches a particular request, the request is *not protected* by Spring Security.
|
||||
====
|
||||
|
||||
The following example demonstrates a single filter chain that only protects requests that begin with `/secured/`:
|
||||
|
||||
[[choosing-security-matcher-request-matchers-java]]
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class CustomSecurityFilterChainConfig {
|
||||
public class PartialSecurityConfig {
|
||||
|
||||
@Bean <1>
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() throws Exception {
|
||||
// ...
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securedFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.securityMatcher("/secured/**") <1>
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.requestMatchers("/secured/user").hasRole("USER") <2>
|
||||
.requestMatchers("/secured/admin").hasRole("ADMIN") <3>
|
||||
.anyRequest().authenticated() <4>
|
||||
)
|
||||
.httpBasic(Customizer.withDefaults())
|
||||
.formLogin(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Requests that begin with `/secured/` will be protected but any other requests are not protected.
|
||||
<2> Requests to `/secured/user` require the `ROLE_USER` authority.
|
||||
<3> Requests to `/secured/admin` require the `ROLE_ADMIN` authority.
|
||||
<4> Any other requests (such as `/secured/other`) simply require an authenticated user.
|
||||
|
||||
[TIP]
|
||||
====
|
||||
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>>.
|
||||
====
|
||||
|
||||
Notice that the `requestMatchers` method only applies to individual authorization rules.
|
||||
Each request listed there must also match the overall `securityMatcher` for this particular `HttpSecurity` instance used to create the `SecurityFilterChain`.
|
||||
Using `anyRequest()` in this example matches all other requests within this particular `SecurityFilterChain` (which must begin with `/secured/`).
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
See xref:servlet/authorization/authorize-http-requests.adoc[Authorize HttpServletRequests] for more information on `requestMatchers`.
|
||||
====
|
||||
|
||||
=== `SecurityFilterChain` Endpoints
|
||||
|
||||
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.
|
||||
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.
|
||||
Such requests would return `404 Not Found`.
|
||||
This is often surprising to users.
|
||||
|
||||
Specifying `http.securityMatcher()` affects what requests are matched by that `SecurityFilterChain`.
|
||||
However, it does not automatically affect endpoints provided by the filter chain.
|
||||
In such cases, you may need to customize the URL of any endpoints you would like the filter chain to provide.
|
||||
|
||||
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`:
|
||||
|
||||
[[security-filter-chain-endpoints-java]]
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecuredSecurityConfig {
|
||||
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() throws Exception {
|
||||
// ...
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(1)
|
||||
public SecurityFilterChain securedFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.securityMatcher("/secured/**") <1>
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.anyRequest().authenticated() <2>
|
||||
)
|
||||
.formLogin(formLogin -> formLogin <3>
|
||||
.loginPage("/secured/login")
|
||||
.loginProcessingUrl("/secured/login")
|
||||
.permitAll()
|
||||
)
|
||||
.logout(logout -> logout <4>
|
||||
.logoutUrl("/secured/logout")
|
||||
.logoutSuccessUrl("/secured/login?logout")
|
||||
.permitAll()
|
||||
)
|
||||
.formLogin(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain defaultFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.anyRequest().denyAll() <5>
|
||||
);
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Requests that begin with `/secured/` will be protected by this filter chain.
|
||||
<2> Requests that begin with `/secured/` require an authenticated user.
|
||||
<3> Customize form login to prefix URLs with `/secured/`.
|
||||
<4> Customize logout to prefix URLs with `/secured/`.
|
||||
<5> All other requests will be denied.
|
||||
|
||||
[NOTE]
|
||||
====
|
||||
This example customizes the login and logout pages, which disables Spring Security's generated pages.
|
||||
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`.
|
||||
Note that Spring Security still provides `POST /secured/login` and `POST /secured/logout` endpoints for you.
|
||||
====
|
||||
|
||||
=== Real World Example
|
||||
|
||||
The following example demonstrates a slightly more real-world configuration putting all of these elements together:
|
||||
|
||||
[[real-world-example-java]]
|
||||
[source,java]
|
||||
----
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class BankingSecurityConfig {
|
||||
|
||||
@Bean <1>
|
||||
public UserDetailsService userDetailsService() {
|
||||
// ensure the passwords are encoded properly
|
||||
UserBuilder users = User.withDefaultPasswordEncoder();
|
||||
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
|
||||
manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
|
||||
manager.createUser(User.withDefaultPasswordEncoder().username("admin").password("password").roles("USER", "ADMIN").build());
|
||||
manager.createUser(users.username("user1").password("password").roles("USER", "VIEW_BALANCE").build());
|
||||
manager.createUser(users.username("user2").password("password").roles("USER").build());
|
||||
manager.createUser(users.username("admin").password("password").roles("ADMIN").build());
|
||||
return manager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(1) <2>
|
||||
public SecurityFilterChain dashBoardFilterChain(HttpSecurity http) throws Exception {
|
||||
@Order(1) <2>
|
||||
public SecurityFilterChain approvalsSecurityFilterChain(HttpSecurity http) throws Exception {
|
||||
String[] approvalsPaths = { "/accounts/approvals/**", "/loans/approvals/**", "/credit-cards/approvals/**" };
|
||||
http
|
||||
.securityMatcher("/account/**", "/loans/**", "/cards/**") <3>
|
||||
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
|
||||
.anyRequest().hasRole("USER") <4>
|
||||
.securityMatcher(approvalsPaths)
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.anyRequest().hasRole("ADMIN")
|
||||
)
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(2) <5>
|
||||
public SecurityFilterChain balanceFilterChain(HttpSecurity http) throws Exception {
|
||||
@Order(2) <3>
|
||||
public SecurityFilterChain bankingSecurityFilterChain(HttpSecurity http) throws Exception {
|
||||
String[] bankingPaths = { "/accounts/**", "/loans/**", "/credit-cards/**", "/balances/**" };
|
||||
String[] viewBalancePaths = { "/balances/**" };
|
||||
http
|
||||
.securityMatcher("/balance/**") <6>
|
||||
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
|
||||
.anyRequest().hasAnyRole("USER", "ADMIN") <7>
|
||||
)
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
.securityMatcher(bankingPaths)
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.requestMatchers(viewBalancePaths).hasRole("VIEW_BALANCE")
|
||||
.anyRequest().hasRole("USER")
|
||||
);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(3) <8>
|
||||
public SecurityFilterChain approvalsFilterChain(HttpSecurity http) throws Exception {
|
||||
@Bean <4>
|
||||
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
|
||||
String[] allowedPaths = { "/user-login", "/user-logout", "/notices", "/contact", "/register" };
|
||||
http
|
||||
.securityMatcher("/loans-approval/**", "/credit-cards-approval/**")<9>
|
||||
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
|
||||
.anyRequest().hasRole("ADMIN") <10>
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.requestMatchers(allowedPaths).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(4) <11>
|
||||
public SecurityFilterChain allowedFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
|
||||
.requestMatchers("/login","/logout","/notices", "/contact", "/register") <12>
|
||||
.permitAll() <13>
|
||||
)
|
||||
.formLogin(Customizer.withDefaults())
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean <14>
|
||||
public SecurityFilterChain defaultFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
|
||||
.anyRequest().authenticated() <15>
|
||||
)
|
||||
.formLogin(Customizer.withDefaults());
|
||||
.formLogin(formLogin -> formLogin
|
||||
.loginPage("/user-login")
|
||||
.loginProcessingUrl("/user-login")
|
||||
)
|
||||
.logout(logout -> logout
|
||||
.logoutUrl("/user-logout")
|
||||
.logoutSuccessUrl("/?logout")
|
||||
);
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
----
|
||||
<1> Begin by configuring authentication settings.
|
||||
<2> Define a SecurityFilterChain instance with @Order(1), which means that this chain will have the highest priority.
|
||||
<3> Specify that the http.securityMatcher applies only to "/account", "/loans", and "/cards" URLs.
|
||||
<4> Requires the user to have the role "USER" to access the URLs "/account", "/loans", and "/cards".
|
||||
<5> Next, create another SecurityFilterChain instance with @Order(2), this chain will be considered second.
|
||||
<6> Indicate that the http.securityMatcher applies only to "/balance" URL.
|
||||
<7> Requires the user to have the role "USER" or the role "ADMIN" to access the URL "/balance"
|
||||
<8> Next, create another SecurityFilterChain instance with @Order(3), this particular security filter chain will be the third in the order of execution.
|
||||
<9> The http.securityMatcher applies only to "/loans-approval" and "/credit-cards-approval" URLs.
|
||||
<10> The user must have the role "ADMIN" to access the URLs "/loans-approval" and "/credit-cards-approval"
|
||||
<11> Define a SecurityFilterChain instance with @Order(4) this chain will be considered fourth.
|
||||
<12> The http.securityMatcher applies only to "/login", "/logout", "/notices", "/contact", "/register" URLs.
|
||||
<13> Allows access to these specific URLs without authentication.
|
||||
<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).
|
||||
<15> Requires the user to be authenticated to access any URL not explicitly allowed or protected by other filter chains.
|
||||
|
||||
<2> Define a `SecurityFilterChain` instance with `@Order(1)`, which means that this filter chain will have the highest priority.
|
||||
This filter chain applies only to requests that begin with `/accounts/approvals/`, `/loans/approvals/` or `/credit-cards/approvals/`.
|
||||
Requests to this filter chain require the `ROLE_ADMIN` authority and allow HTTP Basic Authentication.
|
||||
<3> Next, create another `SecurityFilterChain` instance with `@Order(2)` which will be considered second.
|
||||
This filter chain applies only to requests that begin with `/accounts/`, `/loans/`, `/credit-cards/`, or `/balances/`.
|
||||
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.
|
||||
Requests to this filter chain require the `ROLE_USER` authority.
|
||||
This filter chain does not define any authentication because the next (default) filter chain contains that configuration.
|
||||
<4> 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).
|
||||
Requests that match `/user-login`, `/user-logout`, `/notices`, `/contact` and `/register` allow access without authentication.
|
||||
Any other requests require the user to be authenticated to access any URL not explicitly allowed or protected by other filter chains.
|
||||
|
||||
[[jc-custom-dsls]]
|
||||
== Custom DSLs
|
||||
|
|
Loading…
Reference in New Issue