I’m using Spring Security 3. I have my own authentication provider.
Here is what I have so far:
security-app-context.xml
<authentication-manager>
<authentication-provider user-service-ref="detailsService" />
</authentication-manager>
<beans:bean id="loginSuccessHandler" class="com.myapp.security.LoginSuccessHandler" />
<beans:bean id="loginFailureHandler" class="com.myapp.security.LoginFailureHandler" />
<beans:bean id="detailsService" class="com.myapp.security.UserDetailService" />
UserDetailService
public class UserDetailService implements UserDetailsService {
private DataSource dataSource;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
String hql = "from Users where username = :username";
List<Users> list = null;
try {
IO io = new IO("common_web");
IOQuery query = new IOQuery();
query.setStatement(hql);
query.setParameter(new IOParameter("username", username));
list = io.runQuery(query);
if (list.isEmpty()) {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
// THIS WORKS. I HAVE A VALID USER FROM DB
return (UserDetails) list.get(0);
}
}
This code is just a simple example. At the point of “// THIS WORKS…” I do have a Users record from our database. But when I return this object, I’m still not being authenticated.
Note that Users is a Hibernate table object.
What am I missing?
Just because a UserDetails is returned does not mean that you will be authenticated. The DaoAuthenticationProvider does a number of checks to ensure that the user returned should be authenticated. For example, it ensures that the username and password match, the account is not expired, the account is not locked, etc. A common problem is returning a UserDetails that does not contain any GrantedAuthority’s which results in a UsernamePasswordAuthenticationToken that indicates the user is not authenticated.
Have you tried enabling debug logging for org.springframework.security? This might explain what is wrong. If you are unfamiliar with logging, Spring (and Spring Security) use commons-logging and you can find a logging guide in the Spring reference.
PS As documented in the UserDetailsService interface, loadUserByUsername should never return null. Instead throw a UsernameNotFoundException