Could anyone explain when to override configure(HttpSecurity)
, configure(WebSecurity)
and configure(AuthenticationManagerBuilder)
?
Summary. We can actually consider that WebSecurity is the only external outlet for Spring Security, while HttpSecurity is just the way internal security policies are defined; WebSecurity is aligned to FilterChainProxy , while HttpSecurity is aligned to SecurityFilterChain .
AuthenticationManagerBuilder. parentAuthenticationManager(AuthenticationManager authenticationManager) Allows providing a parent AuthenticationManager that will be tried if this AuthenticationManager was unable to attempt to authenticate the provided Authentication . protected ProviderManager.
A HttpSecurity is similar to Spring Security's XML element in the namespace configuration. It allows configuring web based security for specific http requests. By default it will be applied to all requests, but can be restricted using requestMatcher(RequestMatcher) or other similar methods.
You need to declare SecurityFilterChain and WebSecurityCustomizer beans instead of overriding methods of WebSecurityConfigurerAdapter class. NOTE: If you don't want to change your current code, you should keep Spring Boot version lower than 2.7. 0 or Spring Security version older than 5.7. 1.
configure(AuthenticationManagerBuilder) is used to establish an authentication mechanism by allowing AuthenticationProviders to be added easily: e.g. The following defines the in-memory authentication with the in-built 'user' and 'admin' logins.
public void configure(AuthenticationManagerBuilder auth) { auth .inMemoryAuthentication() .withUser("user") .password("password") .roles("USER") .and() .withUser("admin") .password("password") .roles("ADMIN","USER"); }
configure(HttpSecurity) allows configuration of web based security at a resource level, based on a selection match - e.g. The example below restricts the URLs that start with /admin/ to users that have ADMIN role, and declares that any other URLs need to be successfully authenticated.
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() }
configure(WebSecurity) is used for configuration settings that impact global security (ignore resources, set debug mode, reject requests by implementing a custom firewall definition). For example, the following method would cause any request that starts with /resources/ to be ignored for authentication purposes.
public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers("/resources/**"); }
You can refer to the following link for more information Spring Security Java Config Preview: Web Security
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With