Spring security Principal won't work with @PostConstruct

I have a managedbean which contains this function that returns the username of the logged in user:

public String getConnectedUser( ){  
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null)
        return null;
    Object principal = authentication.getPrincipal();
    if (principal instanceof UserDetails) {
        return ((UserDetails) principal).getUsername();
    } else {
        return principal.toString();
    }

I want to get the user with my DAO using the username I get from spring security. When I call it inside the @PostConstruct method it doesn't return anything.

    @PostConstruct
public void init() {

user = utilisateurService.getUtilisateurByLogin( getConnectedUser());

but when I call it in JSF, it shows me the correct logged in username:

        <h:outputText
            value="Logged as : #{testMB.getConnectedUser()}" />

in conclusion : with Init function I get nothing in the view , with the JSF call I get the username, can someone help me out?

EDIT : i run some tests and it appears that the authentication is null , even tho i'm logged in

1 answer

  • answered 2020-08-13 05:10 SKumar

    I think it makes sense that Spring Security principal is not available in PostConstruct.

    PostConstruct on DAO would have been called at the time of application startup. At that time, there would be no logged in user. But, when you browse through a JSF page, there you might have logged in and that's why Principal is available there.

    Spring Security Filter chain will get invoked when you visit application url.

    I suggest you to call this method during your regular DAO method calls. If you are logged in, then Principal should be available.

    @Repository
    public class SomeDao
    {
    
    public String someDaoMethod() {
      getConnectedUser();
      ....
    }
    private String getConnectedUser( ){  
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null)
            return null;
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        } else {
            return principal.toString();
        }