Spring Security Service Configuration
I am trying to prototype a Java EE application using different frameworks. Everything works fine except for the security level. I decided to use Spring Security configured with Spring config.
The code looks like this:
Spring Security Configuration
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected UserDetailsService userDetailsService () {
return this.userDetailsService;
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login/authenticate")
.failureUrl("/login?error=bad_credentials")
.and()
.logout()
.logoutUrl("/signout")
.deleteCookies("JSESSIONID")
.and()
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").permitAll()
.and()
.csrf();
}
}
Detailed user service
@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService
{
public static final Logger log = Logger.getLogger(MyUserDetailsService.class);
public MyUserDetailsService() {
}
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
final User user = getSystemUser(userName);
final List<GrantedAuthority> authorities = getUserAuthorities(user);
return buildUserForAuthentication(user, authorities);
}
private User buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
//...
}
private User getSystemUser(String alias) {
//...
}
private List<GrantedAuthority> getUserAuthorities(User user) {
//...
return null;
}
}
What I expect from this code is that when /login/authenticate
reached with user and password parameters, the underlying Spring code calls my user service, but that never happens.
What am I missing?
I am using spring-security 3.2.3.RELEASE.
+3
source to share
1 answer
You have to register your custom ServiceDetailsService with Authentication,
@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(this.userDetailsService);
}
for 3.2.3 config should be
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.userDetailsService);
}
+2
source to share