简体   繁体   中英

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

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();
    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM