使用Spring Security Authentication存储userId

时间:2015-09-08 22:12:08

标签: 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";
    }

服务

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

        }

最后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;
    }

修改:用户模型:

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

2 个答案:

答案 0 :(得分:4)

如果应用程序是Web应用程序,

SecurityContextHolder.getContext().setAuthentication(result);会将身份验证对象放在SecurityContext中,该对象本身在会话中维护。

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

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

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

并在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());

}

现在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();

答案 1 :(得分:0)

您可以拥有自己的AuthenticationProvider来处理您的登录信息:

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

}
}

然后你可以得到这样的当前用户:

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