irisk irisk - 3 months ago 12
Java Question

User details store best practies

It is possible to extends from

org.springframework.security.core.userdetails.User

and create your own implementation of it to hold more information about a user, not only username/password/authorities. So, we can make something like

public class CustomUser extends User {
private MyEntityUser user;
// getters/setters/contructor
}


And do not load from database user information more than one time?

Is that legal? Or exists another palce for this functionality?

Answer

That's one of the good ways to solve your problem. From the Java documentation, there are three appropriate approaches:

Developers may use this class directly [1], subclass it [2], or write their own UserDetails implementation from scratch [3].

On one of my projects I've picked up the third strategy and used the following hierarchy:

class AccountAuthDetails extends Account implements UserDetails { ... }
class Account { ... }

I didn't have a need in org.springframework.security.core.userdetails.User then.