Answer the question
In order to leave comments, you need to log in
How to create different classes for different roles in Spring Security?
For role-based authorization in the application, Spring Security is used, so I have a User entity with a Set<Role> roles
. Due to the fact that different roles need very different sets of fields, I want to make it a User
general abstract class and inherit from it specific classes for each role: SimpleUser
, Admin
etc.
Spring Security uses UserDetailsService for authorization, here is my implementation:
@Service("securityUserService")
public class SecurityUserService implements UserDetailsService {
private final UserRepository repository;
public SecurityUserService(UserRepository repository) {
this.repository = repository;
}
@Override
public AuthorizedUser loadUserByUsername(String email) throws UsernameNotFoundException {
User user = repository.getByEmail(email.toLowerCase());
if (user == null) {
throw new UsernameNotFoundException("User " + email + " is not found");
}
return new AuthorizedUser(user);
}
}
Answer the question
In order to leave comments, you need to log in
The authentication and authorization system does not require any additional entities and classes serving them
different roles need very different sets of fields
I would not create classes for each of the roles, but would implement it as follows:
1) Create a User class. Flag @MappedSuperclass
. Put common fields there: username, password, etc.
2) Next, create the necessary classes and extend the User class. For example, Customer, Author, etc. And specify all fields specific to each of the classes in them.
3) Next, for example, you can create a Builder pattern, which, when creating an entity by default, will assign roles corresponding to the class.
PS Don't forget to also implement the UserDetails interface required by Spring Security.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question