问题
I want to make a config file to configure TLS and Oauth2 in my SecureConfig.java
The tls config:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER);
}
The Oauth2.0 config:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.requiresChannel()
.anyRequest()
.requiresSecure();
}
What is the better way to use these two in the same config file and method? Does the and() work fine?
Like that:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
.requiresChannel()
.anyRequest()
.requiresSecure();
}
回答1:
Issue with your two filter chain approach (Regardless of what your configure inside the methods
- Spring security is a chain of filters see Filters in Spring Security Filter Chain
- By implementing
configure(HttpSecurity http)
twice, you have createdtwo spring-security-filter-chain
s. - Since you are not providing
http.requestMatcher(...)
, both chains are applicable to every url. And it is a problem for spring security as it will only apply one filter chain to a particular request. So if you try to start up your app, it will fail to start with an error - You can make your app start by defining an
@Order
annotation so spring security chooses the one with the lower number applicable for a url. But since both chains are applicable to every url as per your config, the filter chain with lower@Order
overrides the filter chain with higher@Order
making it useless
Solution
- Use one class that extends
WebSecurityConfigurerAdapter
so you have one security filter chain
Channel Security vs Authentication vs Authorisation
Security is mainly 4 aspects. Authentication, Authorisation, Integrity and Confidentiality. Rest API under https security
What you have in the filter is about authentication. You may have also defined some urls need some roles which is Authorisation. So that config was about those 2 aspects
By
requiresSecure()
you are addressingConfidentiality
. i.e If you userequiresSecure()
without the first one, you know you are not talking to some middle man but you won't know who you are talking to because that is what the purpose of authentication.Since they are complimentary security aspects, They can be combined together and spring will create one filter chain where the first filter ensures you are first talking over https by placing
ChannelProcessingFilter
as the first barrier
来源:https://stackoverflow.com/questions/62753011/http-security-config-for-tls-and-oauth2-in-the-same-method