Spring Security: Basic Steps & Configuration
Spring Security: Basic Steps & Configuration
In Memory Authentication:
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration
extends WebSecurityConfigurerAdapter
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
Spring Security
● JDBC Authentication:
@Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.withDefaultSchema()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
Spring Security
● LDAP Authentication:
@Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups");
}
Spring Security
Multiple HttpSecurity:
@EnableWebSecurity
public class MultiHttpSecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) { 1
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
Spring Security
@Configuration
@Order(1)
● public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
● Here @Order specify which WebSecurityConfigurerAdapter should be considered first.
● The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start
with /api/.
Spring Security
@Configuration 4
public static class FormLoginWebSecurityConfigurerAdapter extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
}
● If URL does not start with /api then this configuration would be used.
Spring Security
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { WebSecurityConfiguration.class };
}
...
}
Spring Security
●
Step 4: Configure the springSecurityFilterChain.
– This can be done by extending '
AbstractSecurityWebApplicationInitializer ' and
optionally overriding methods to customize the
mapping.
– (The 'AbstractSecurityWebApplicationInitializer'
class is used to registers the DelegatingFilterProxy
to use the springSecurityFilterChain before any
other registered Filter.)
Spring Security