Customize new Authentication Context

Is there a good way to customize the authentication context, to also hold a e.g. JPA User Entity?
Before I had an own class that held the “user repository” and a method which fetched the user by the current security context by spring

For this you could also make the entity implement UserDetail

Then you can directly return your entity in UserDetailsServiceImpl

And then you don’t need to fetch the user each time because it’s contained in the SecurityContext

Does that work with an external user management provider? OAuth2 login and so on

All spring based login mechanism provide a “user” / principal based on the Authentication interface, this is also the base interface of this Implementation - therefore anything should work out of the box if you supply your security correctly to the spring provided security context

Okay, I’ll look into that, thanks :slightly_smiling_face:

You can also continue to use your own class and have the AuthenticationContext injected to get some user identifier to use with the repository
Take a look at the example in the following ticket

BTW, in next release AuthenticationContext should also have a getPrincipalName method that will basically be Authentication.getName

That repo is private :wink:

Ops, sorry :person_facepalming:

public class AuthenticatedUser implements Serializable {

    private final transient UserRepository userRepository;
    private final AuthenticationContext authContext;

    public AuthenticatedUser(AuthenticationContext authContext, UserRepository userRepository) {
        this.userRepository = userRepository;
        this.authContext = authContext;

    public Optional<User> get() {
        return authContext.getAuthenticatedUser(UserDetails.class)
                .map(userDetails -> userRepository.findByUsername(userDetails.getUsername()));

    public void logout() {


For my liking to many database calls if the security context already contains the user :sweat_smile: at least any change in the database is reflected immediately :grimacing:

I agree. GetAuthenticatedUser may be enough in many cases, but sometimes additional info may be needed.
Of course the above class can be improved in many ways :slightly_smiling_face:

IMO the name of the class is strange

Sounds like an entity but is a Service that calls the database

And I share the opinion of @quirky-zebra

Plus why does it expose logout when I can directly inject AuthenticationContext where I want to use logout?

Looks superfluous

That one was just an example based on a start project class. Logout is there only to avoid changing existing code.