I am looking to use Spring Security w/ MySql to store Users, Roles, Permissions (authorities). I have done the following:
ApplicationUser (id, firstName, lastName, username, password, roles )
ApplicationRole (id, name, description, permissions ) implements GrantedAuthority
ApplicationPermission (id, name, description) implements GrantedAuthority
I created a class that implements UserDetailService. In the loadUserByUsername method I doing the following:
ApplicationUser applicationUser = userRepository.findByUsername(username);
if(applicationUser == null) {
throw new UsernameNotFoundException(username);
}
// Extract role/role permission grantedAuthorities from db user
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (Role role: applicationUser.getRoles()) {
grantedAuthorities.add(role);
grantedAuthorities.addAll(role.getPermissions());
}
return new User(applicationUser.getUsername(), applicationUser.getPassword(), grantedAuthorities);
However, this still leaves me a bit confused and here are a few of my questions...
I think my problem is that I am confused as to when/how to properly implement UserDetail and UserDetailService making sure I am loading the authorities from the database and setting them each time a user logs in. Additionally, is there any point in implementing GrantedAuthority with my ApplicationRole and ApplicationPermission class the way I am?
It's not necessary and I wouldn't recommend it either. It's good to keep these different aspects of your application separate. As far as I know it's a common practice to fetch the roles in your custom UserDetailsService
and wrap their textual representation in a SimpleGrantedAuthority
(ie their name). Note that to differentiate between roles and authorities within Spring Security you have to prefix roles with the ROLE_
tag by default (see hasRole
and hasAuthority
access-control expressions).
Having a custom UserDetails
implementation is not necessary but might have benefits, for example you can store extra fields that are specific to your application. The default implementation is org.springframework.security.core.userdetails.User
, most of the time you can just extend this one.
See #1
is there any point in implementing GrantedAuthority with my ApplicationRole and ApplicationPermission class the way I am?
It wouldn't make any sense, no. Many use-cases are covered by the existing implementations, but for the most simple use-cases you can just stick to SimpleGrantedAuthority
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.