Chaibi Alaa
Chaibi Alaa

Reputation: 1386

Store the userId with Spring Security Authentication

I need to get the userId when the authentication is loading the login, so that I can store it and use it later to gather more information about the by its ID.

Here is my login bean :

 public String login() {
        try {
            Authentication request = new UsernamePasswordAuthenticationToken(this.getUsername(), this.getPassword());
            Authentication result = authenticationManager.authenticate(request);
            SecurityContextHolder.getContext().setAuthentication(result);
            sessionMap.put("UsernameOnLogin", this.getUsername());

        } catch (AuthenticationException e) {
            e.printStackTrace();
            sessionMap.clear();
            return "error.xhtml";
        }
        return "i.xhtml";
    }

And the Service

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

            empsuite.model.UserData domainUser = userloginDAO.getUsername(username);

            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;

            return new User(
                    domainUser.getUsername(),
                    domainUser.getPassword(),
                    enabled,
                    accountNonExpired,
                    credentialsNonExpired,
                    accountNonLocked,
                    getAuthorities(1));

        }

And finally the DAO function to get the username to perform a login :

public UserData getUsername(String username) {
        List<UserData> userList = new ArrayList<UserData>();
        Query query = openSession().createQuery("from UserData u where u.username = :Username");
        query.setParameter("Username", username);
        userList = query.list();
        if (userList.size() > 0)
            return userList.get(0);
        else
            return null;
    }

Edit : User Model :

public class UserData implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    int iduser;
    String username;
    String password;
    int accountstatus;
    //Profile OLD
    String nomprofile;
    String prenprofile;
    String mailprofile;
    String adressprofile;
    int phoneprofile;
    Date datenaissanceprofile;
    char sexeuser;
    String imagepath;
    public int getIduser() {
        return iduser;
    }
    public void setIduser(int iduser) {
        this.iduser = iduser;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public int getAccountstatus() {
        return accountstatus;
    }
    public void setAccountstatus(int accountstatus) {
        this.accountstatus = accountstatus;
    }


    public String getNomprofile() {
        return nomprofile;
    }
    public void setNomprofile(String nomprofile) {
        this.nomprofile = nomprofile;
    }
    public String getPrenprofile() {
        return prenprofile;
    }
    public void setPrenprofile(String prenprofile) {
        this.prenprofile = prenprofile;
    }
    public String getMailprofile() {
        return mailprofile;
    }
    public void setMailprofile(String mailprofile) {
        this.mailprofile = mailprofile;
    }
    public String getAdressprofile() {
        return adressprofile;
    }
    public void setAdressprofile(String adressprofile) {
        this.adressprofile = adressprofile;
    }
    public int getPhoneprofile() {
        return phoneprofile;
    }
    public void setPhoneprofile(int phoneprofile) {
        this.phoneprofile = phoneprofile;
    }
    public Date getDatenaissanceprofile() {
        return datenaissanceprofile;
    }
    public void setDatenaissanceprofile(Date datenaissanceprofile) {
        this.datenaissanceprofile = datenaissanceprofile;
    }
    public char getSexeuser() {
        return sexeuser;
    }
    public void setSexeuser(char sexeuser) {
        this.sexeuser = sexeuser;
    }
    public String getImagepath() {
        return imagepath;
    }
    public void setImagepath(String imagepath) {
        this.imagepath = imagepath;
    }

Upvotes: 6

Views: 8910

Answers (2)

seenukarthi
seenukarthi

Reputation: 8624

SecurityContextHolder.getContext().setAuthentication(result); will put the authentication object in SecurityContext which itself maintained in session if the application is a web application.

Instead of storing the username in session you can retrieve the Authentication object using the following code.

SecurityContext securityContext = SecurityContextHolder.getContext();
Object principal;
String username;
if(null != securityContext.getAuthentication()){
   principal = securityContext.getAuthentication().getPrincipal();
   username = securityContext.getAuthentication().getName();
}

Value of username will be the username used in authentication. Value of principal will be the principal object. Many of the authentication providers will create a UserDetails object as the principal.

Update:

If you want to store additional information you can extend org.springframework.security.core.userdetails.User and have the additional informations as properties of that class.

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;

public class CustomUser extends User {

    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities,int id) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        setId(id);
    }
}

And in loadUserByUsername return CustomUser instead of User.

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    empsuite.model.UserData domainUser = userloginDAO.getUsername(username);

    boolean enabled = true;
    boolean accountNonExpired = true;
    boolean credentialsNonExpired = true;
    boolean accountNonLocked = true;

    return new CustomUser(
            domainUser.getUsername(),
            domainUser.getPassword(),
            enabled,
            accountNonExpired,
            credentialsNonExpired,
            accountNonLocked,
            getAuthorities(1),
            domainUser.getId());

}

Now securityContext.getAuthentication().getPrincipal() will return CustomUser object. So you can get the ID by ((CustomUser)securityContext.getAuthentication().getPrincipal()).getId()

SecurityContext securityContext = SecurityContextHolder.getContext();
CustomUser user;
if(null != securityContext.getAuthentication()){
   user = (CustomUser) securityContext.getAuthentication().getPrincipal();
}
int id = user.getId();

Upvotes: 11

xierui
xierui

Reputation: 1055

You can have your own AuthenticationProvider to handler your login:

@Component
public class AuthenticationProviderBean implements AuthenticationProvider {

@Autowired
private UserloginDAO userloginDAO;

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = null;
    User user = userloginDAO.getUsername(username);
    if(user == null || !userLoginDAO.auth(user.getPassword(), password)){
        throw new BadCredentialsException("Login Unauthenticated");
    }
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,
                            password, Arrays.asList(new MyGrantedAuthority(user)));
    token.setDetails(user);
    return token;
}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
}

public class MyGrantedAuthority implements GrantedAuthority{

    private static final long serialVersionUID = 5202669007419658413L;

    private UserData user;

    public MyGrantedAuthority() {
        super();
    }

    public MyGrantedAuthority(UserData user){
        this.user = user;
    }

    @Override
    public String getAuthority() {
        return user.getRole();
    }

}
}

Then you can get current user like this:

User user = (User)SecurityContextHolder.getContext().getAuthentication.getDetails();

Upvotes: 0

Related Questions