使用Spring Security身份验证存储userId

Cha*_*laa 1 java spring

身份验证正在加载登录名时,我需要获取userId,以便我可以存储它并在以后使用它通过其ID收集有关的更多信息。

这是我的登录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";
    }
Run Code Online (Sandbox Code Playgroud)

和服务

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

        }
Run Code Online (Sandbox Code Playgroud)

最后,DAO函数获取用户名以执行登录:

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;
    }
Run Code Online (Sandbox Code Playgroud)

编辑:用户模型:

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;
    }
Run Code Online (Sandbox Code Playgroud)

Kar*_*gam 6

SecurityContextHolder.getContext().setAuthentication(result);SecurityContext如果应用程序是Web应用程序,则会将本身维护的身份验证对象放入会话中。

无需在会话中存储用户名,您可以Authentication使用以下代码检索对象。

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

username将是身份验证中使用的用户名。值principal将是主要对象。许多身份验证提供程序将创建一个UserDetails对象作为主体。

更新:

如果要存储其他信息,则可以扩展org.springframework.security.core.userdetails.User并将其他信息作为该类的属性。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

作为loadUserByUsername回报CustomUser而不是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());

}
Run Code Online (Sandbox Code Playgroud)

现在securityContext.getAuthentication().getPrincipal()将返回CustomUser对象。所以你可以ID通过((CustomUser)securityContext.getAuthentication().getPrincipal()).getId()

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