使用Spring Security身份验证存储userId [英] Store the userId with Spring Security Authentication

查看:157
本文介绍了使用Spring Security身份验证存储userId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的登录bean:

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

和服务

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函数以获取用户名以执行登录:

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

用户模型:

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

推荐答案

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

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

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

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

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

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.

更新:

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

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

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对象.因此,您可以通过((CustomUser)securityContext.getAuthentication().getPrincipal()).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();

这篇关于使用Spring Security身份验证存储userId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆