Spring security - Configuring an application to use spring security
We can configure spring security by editing web.xml
or by extending the WebSecurityConfigurerAdapter
implementation. In both approaches, we define the providers for authentication and authorization and descriptions of application scopes that need authentication and/or authorization. We can specify what to secure and how to secure it.
Web SecurityConfiguration Adapter is the java configuration class for configuring web-based security, where all spring security related injection happens.
@Configuration
@EnableWebSecurity
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
// ...
}
@EnableWebSecurity
is used for spring security java configuration. Add this annotation with @configuration
on top of your security java class that extends WebSecurityConfigurerAdapter
.
Override the configure(WebSecurity web)
& configure(HttpSecurity http)
. This is the replacement of xml based configurations like <http>
and <form login>
. This way you can limit requested urls coming from specific urls also enable form based log in.
e.g.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@SuppressWarnings({ "PMD.SignatureDeclareThrowsException" })
protected void configure(final HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Make all endpoints not explicitly ignored secure and apply the JWT authentication filter to them
http.authorizeRequests().anyRequest().authenticated().and().addFilterBefore(
new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
// JWTAuthenticationFilter is a Custom Spring Security filter that determines if a request's JWT is signed by Apigee or not.
}
@Override
public void configure(WebSecurity web) {
// Do not apply security to the following endpoints
web.ignoring().antMatchers(
"/",
"/actuator",
"/actuator/info",
"/actuator/health",
"/favicon.ico");
}
}