In the end I had to change my authentication handler onAuthenticationSuccess. In spring there are authentication and login in the lifecycle of the login process. During authentication the user is, well, authenticated, but not yet logged into the application (ie only its credentials were deemed valid, but the rest of the application is not aware of the user yet.)
I changed my security.xml to:
<beans:bean id="authHandler" class="mypackage.activedirectory.ActiveDirectoryAuthenticationHandler"
...
<form-login login-page="/login" authentication-failure-handler-ref="authHandler"
authentication-success-handler-ref="authHandler" />
And here is the class:
public class ActiveDirectoryAuthenticationHandler extends MyAuthenticationHandler {
@Autowired
private UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth)
throws IOException, ServletException {
String username= auth.getName();
User user= userService.findByUsername(username);
if (user == null) {
user= new User();
//set user properties
}
try {
userService.save(user);
} catch (EntityException e) {
System.out.println(e.getMessage());
}
super.onAuthenticationSuccess(req, resp, auth);
}
}
I still haven't figured out how to handle AD specific errors (like user is blocked, or password expired), right now it shows my application default login error message.