Search code examples
springspring-securityzk

how to get my Current custom User in Spring Security?


I am using spring security for authentication. I created a custom user who extends from User ,then I used it in my customServiceDetails (implementation of UserDetailsService ) , I want to be able to get my custom user, so I tried to do this :

public class MyUser extends User implements Serializable {


    private static final long serialVersionUID = 1L;

    private String uuid;

    public MyUser(String username, String password, boolean enabled,
            boolean accountNonExpired, boolean credentialsNonExpired,
            boolean accountNonLocked,
            Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, authorities);

    }

    public MyUser(String username, String password, String uuid,
            boolean enabled, boolean accountNonExpired,
            boolean credentialsNonExpired, boolean accountNonLocked,
            Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, authorities);
        this.uuid = uuid;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
}

I tried to get the current user by doing this but it's not working :

 (MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

I wonder if there is any suggestion ?


Solution

  • I am using Zk framework so the solution was like that :

    MyUser user =(MyUser)((UsernamePasswordAuthenticationToken) Executions.getCurrent().getUserPrincipal()).getPrincipal();
    

    i get the current custom user from UsernamePasswordAuthenticationToken