Spring security with database and multiple roles?
I am trying to build an application using spring 3.0. Now I decided to try my hand at spring-security and hibernate. I have already seen that it is possible to support it with databasem and I have seen a link to define your own queries?
Now the problem is that the tutorials I find are not very clear and that they assume that a user can only have one role. I want to give multiple users multiple roles.
So, I was thinking about the database schema row by row:
User:
- user_id
- Username
- password
- registrationDate
USER_ROLE:
- user_id
- role_id
Role:
- role_id
- RoleName
Now I was wondering if anyone has any pointers to helpful tips / tips / comments.
a source to share
You need to implement your own UserDetails (supports multiple roles per user). This custom UserDetails implementation is then returned by your own UserDetailsService that was injected into your daoAuthenticationProvider .
See also my answer @ Spring Security 3 Database Authentication with Hibernate for a complete example.
a source to share
Something like that:
public class CustomUserService implements UserDetailsService {
private UserDao userDao;
public CustomUserService(UserDao u) {
userDao = u;
}
public UserDetails loadUserByUsername(String username) {
CustomUser user = userDao.getUser(username);
if (user == null)
throw new UserNotFoundException("User "+username+" does not exist");
return user;
}
}
And your UserDao implementation is a simple DAO that can easily use hibernate annotations and assign multi-user roles to your CustomUser object. Pretty basic.
a source to share