自定义用户信息的弹簧安全性 [英] spring security with custom user details

查看:95
本文介绍了自定义用户信息的弹簧安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



到目前为止,我在applicationContext-Security中的内容是:

 < beans:bean id =userDetailsS​​erviceclass =org.intan.pedigree.service.UserDetailsS​​erviceImpl>< / beans:bean> 

< http auto-config ='true'>
< intercept-url pattern =/ **access =ROLE_USER/>
< / http>

< bean:bean id =daoAuthenticationProvider
class =org.springframework.security.authentication.dao.DaoAuthenticationProvider>
< beans:property name =userDetailsS​​erviceref =userDetailsS​​ervice/>
< / beans:bean>

< beans:bean id =authenticationManager
class =org.springframework.security.authentication.ProviderManager>
< beans:property name =providers>
< beans:list>
< beans:ref local =daoAuthenticationProvider/>
< / beans:list>
< / beans:property>
< / beans:bean>


< authentication-manager>
< authentication-provider user-service-ref =userDetailsS​​ervice>
< password-encoder hash =plaintext/>
< / authentication-provider>
< / authentication-manager>

我的userDetailsS​​ervice实现如下所示:

  package org.intan.pedigree.service; 

import org.intan.pedigree.dao.UserEntityDAO;
import org.intan.pedigree.dao.UserEntityDAOImpl;
import org.intan.pedigree.form.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsS​​ervice;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Service(userDetailsS​​ervice)
public class UserDetailsS​​erviceImpl implements UserDetailsS​​ervice {
$ b $ @Autowired
private UserEntityDAO dao;
@Autowired
私有汇编程序汇编程序;

@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException,DataAccessException {
$ b $ UserDetails userDetails = null;
UserEntity userEntity = dao.findByName(username);
if(userEntity == null)
throw new UsernameNotFoundException(user not found);

return assembler.buildUserFromUserEntity(userEntity);


我的汇编程序如下所示:

  package org.intan.pedigree.service; 

import java.util.ArrayList;
import java.util.Collection;

import org.intan.pedigree.form.SecurityRoleEntity;
import org.intan.pedigree.form.UserEntity;
//导入org.springframework.security.core.GrantedAuthority;
// import org.springframework.security.core.authority.GrantedAuthorityImpl;
//导入org.springframework.security.core.userdetails.User;
导入org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service(assembler)
public class Assembler {

@Transactional(readOnly = true)
UserUserFromUserEntity(UserEntity userEntity){

字符串用户名= userEntity.getUsername();
String password = userEntity.getPassword();
boolean enabled = userEntity.isActive();
布尔accountNonExpired = userEntity.isActive();
布尔credentialsNonExpired = userEntity.isActive();
布尔accountNonLocked = userEntity.isActive();
收藏<授权授权> authority = new ArrayList< GrantedAuthority>(); (SecurityRoleEntity role:userEntity.getUserSecurityRoleEntity()){
authorities.add(new GrantedAuthorityImpl(role.getName()))的
;
}

用户用户=新用户(用户名,密码,启用,
accountNonExpired,credentialsNonExpired,accountNonLocked,权限);
返回用户;


$ / code $ / pre

现在用户实体是:

  package org.intan.pedigree.form; 

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name =user)
public class UserEntity {

@Id
@GeneratedValue
@Column( name =ID)
private int id;
@Column(name =first_name)
private String first_name;
@Column(name =family_name)
private String last_name;
@Column(name =dob)
私人日期dob;
@Column(name =password)
private String password;
@Column(name =username)
私人字符串用户名;
@Column(name =active)
@NotNull
private boolean isActive;
@Column(name =user_types_id)
private int user_types_id;
@Column(name =confirm_password)
public String confirmPassword;
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name =user_address,joinColumns = {@JoinColumn(name =user_id)},
inverseJoinColumns = {@JoinColumn name =address_id)})
private Set< Address> userAddress = new HashSet< Address>(0);
/ ********************************************* ********************************** /
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name =user_security_role,joinColumns = {@JoinColumn(name =user_id)},
inverseJoinColumns = {@JoinColumn(name =security_role_id)})
private Set< SecurityRoleEntity> userSecurityRoleEntity = new HashSet< SecurityRoleEntity>(0);

public Set< Address> getUserAddress(){
返回this.userAddress;
}

public void setUserAddress(Set< Address> userAddress){
this.userAddress = userAddress;
}
/ **************************************** ************************************* /

public Set< SecurityRoleEntity> ; getUserSecurityRoleEntity(){
返回this.userSecurityRoleEntity;
}

public void setUserSecurityRoleEntity(Set< SecurityRoleEntity> userSecurityRoleEntity){
this.userSecurityRoleEntity = userSecurityRoleEntity;
}


public boolean isActive(){
return isActive;
}

public void setActive(boolean isActive){
this.isActive = isActive;
}

public String getConfirmPassword(){
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword){
this.confirmPassword = confirmPassword;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getFirst_name(){
return first_name;
}
public void setFirst_name(String first_name){
this.first_name = first_name;
}
public String getLast_name(){
return last_name;
}
public void setLast_name(String last_name){
this.last_name = last_name;
}
public Date getDob(){
return dob;
}
public void setDob(Date dob){
this.dob = dob;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
public int getUser_types_id(){
return user_types_id;
}
public void setUser_types_id(int user_types_id){
this.user_types_id = user_types_id;
}


}

我的用户界面界面是:

  package org.intan.pedigree.dao; 

import java.util.List;

import org.intan.pedigree.form.UserEntity;


public interface UserEntityDAO {
public void removeUserEntity(Integer id);
公共列表< UserEntity> listUserEntity();
public void addUserEntity(UserEntity user);
public void updateUserEntity(UserEntity user);
public UserEntity getUserEntityByID(Integer id);
public UserEntity findByName(String username);
}

并且执行是:

  @Repository 
public class UserEntityDAOImpl implements UserEntityDAO {
$ b $ @Autowired
private SessionFactory sessionFactory;

public void addUserEntity(UserEntity user){
try {
sessionFactory.getCurrentSession()。save(user);
} catch(Exception e){
System.out.println(e);


$ b $ public UserEntity findByName(String username){
UserEntity user =(UserEntity)sessionFactory.getCurrentSession()。createQuery(
select你可以在u.username ='+ username +')中填写用户名u;
返回用户;


$ public UserEntity getUserEntityByID(Integer id){
UserEntity user =(UserEntity)sessionFactory.getCurrentSession()。createQuery(
select u形成用户你在哪里id ='+ id +');
返回用户;
}
public void updateUserEntity(UserEntity user){
try {
sessionFactory.getCurrentSession()。update(user);
} catch(Exception e){
System.out.println(e);
}
}

public List< UserEntity> listUserEntity(){

return sessionFactory.getCurrentSession()。createQuery(from User)
.list();

$ b $ public void removeUserEntity(Integer id){
UserEntity user =(UserEntity)sessionFactory.getCurrentSession()。load(
UserEntity.class,id);
if(null!= user){
sessionFactory.getCurrentSession()。delete(user);
}

}
}

现在当我尝试在tomcat上部署,我得到以下异常:

  org.springframework.beans.factory.BeanCreationException:创建bean with名称'userDetailsS​​ervice':注入自动装配依赖失败;嵌套异常
是org.springframework.beans.factory.BeanCreationException:无法自动装载字段:private org.intan.pedigree.dao.UserEntityDAO org.intan.pedigree.service.UserDetailsS​​
erviceImpl.dao;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:[org.intan.pedigree.dao.UserEntityDAO]类型的匹配bean没有找到依赖关系的
:期望至少有1个符合此依赖关系的autowire候选者的Bean 。依赖注释:{@ org.springframework.beans.factory.annotatio
n.Autowired(required = true)}

而不是我做什么我不知道它有什么问题。任何建议都会受到欢迎。



非常感谢

解决方案

I在您的上下文中没有看到 UserEntityDAOImpl Assembler bean的声明,并且没有组件扫描来自动检测它。

您需要将它们与 UserDetailsS​​erviceImpl 一起声明,或者添加<上下文:组件扫描> 某处。


I am trying to apply security in my spring application using database tables.

What I have so far in my applicationContext-Security is:

<beans:bean id="userDetailsService" class="org.intan.pedigree.service.UserDetailsServiceImpl"></beans:bean>

<http auto-config='true'>
    <intercept-url pattern="/**" access="ROLE_USER" />
</http>

 <beans:bean id="daoAuthenticationProvider"
    class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
    <beans:property name="userDetailsService" ref="userDetailsService" />
</beans:bean>

<beans:bean id="authenticationManager"
    class="org.springframework.security.authentication.ProviderManager">
    <beans:property name="providers">
        <beans:list>
            <beans:ref local="daoAuthenticationProvider" />
        </beans:list>
    </beans:property>
</beans:bean>


<authentication-manager>
    <authentication-provider user-service-ref="userDetailsService">
        <password-encoder hash="plaintext" />
    </authentication-provider>
</authentication-manager>

my implementation of userDetailsService looks as follows:

    package org.intan.pedigree.service;

import org.intan.pedigree.dao.UserEntityDAO;
import org.intan.pedigree.dao.UserEntityDAOImpl;
import org.intan.pedigree.form.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserEntityDAO dao;
    @Autowired
    private Assembler assembler;

    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException {

        UserDetails userDetails = null;
        UserEntity userEntity = dao.findByName(username);
         if (userEntity == null)
              throw new UsernameNotFoundException("user not found");

        return  assembler.buildUserFromUserEntity(userEntity);
    }
}

my assembler looks as follows:

package org.intan.pedigree.service;

import java.util.ArrayList;
import java.util.Collection;

import org.intan.pedigree.form.SecurityRoleEntity;
import org.intan.pedigree.form.UserEntity;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.authority.GrantedAuthorityImpl;
//import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("assembler")
public class Assembler {

  @Transactional(readOnly = true)
  User buildUserFromUserEntity(UserEntity userEntity) {

    String username = userEntity.getUsername();
    String password = userEntity.getPassword();
    boolean enabled = userEntity.isActive();
    boolean accountNonExpired = userEntity.isActive();
    boolean credentialsNonExpired = userEntity.isActive();
    boolean accountNonLocked = userEntity.isActive();
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (SecurityRoleEntity role : userEntity.getUserSecurityRoleEntity()) {
      authorities.add(new GrantedAuthorityImpl(role.getName()));
    }

    User user = new User(username, password, enabled,
      accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    return user;
  }
}

now the user entity is:

    package org.intan.pedigree.form;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="user")
public class UserEntity {

    @Id
    @GeneratedValue
    @Column(name="ID")
    private int id;
    @Column(name="first_name")
    private String first_name;
    @Column(name="family_name")
    private String last_name;
    @Column(name="dob")
    private Date dob;
    @Column(name="password")
    private String password;
    @Column(name="username")
    private String username;
    @Column(name="active")
        @NotNull
    private boolean isActive;
    @Column(name="user_types_id")
    private int user_types_id;
    @Column(name="confirm_password")
    public String confirmPassword;
    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_address", joinColumns = { @JoinColumn(name = "user_id") },
            inverseJoinColumns = { @JoinColumn(name = "address_id") })
    private Set<Address> userAddress = new HashSet<Address>(0);
    /*******************************************************************************/
    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_security_role", joinColumns = { @JoinColumn(name = "user_id") },
            inverseJoinColumns = { @JoinColumn(name = "security_role_id") })
    private Set<SecurityRoleEntity> userSecurityRoleEntity = new HashSet<SecurityRoleEntity>(0);

    public Set<Address> getUserAddress(){
        return this.userAddress;
    }

    public void setUserAddress(Set<Address> userAddress) {
        this.userAddress = userAddress;
    }
    /*****************************************************************************/

    public Set<SecurityRoleEntity> getUserSecurityRoleEntity(){
        return this.userSecurityRoleEntity;
    }

    public void setUserSecurityRoleEntity(Set<SecurityRoleEntity> userSecurityRoleEntity) {
        this.userSecurityRoleEntity = userSecurityRoleEntity;
    }


    public boolean isActive() {
        return isActive;
    }

    public void setActive(boolean isActive) {
        this.isActive = isActive;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }
    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirst_name() {
        return first_name;
    }
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
    public String getLast_name() {
        return last_name;
    }
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getUser_types_id() {
        return user_types_id;
    }
    public void setUser_types_id(int user_types_id) {
        this.user_types_id = user_types_id;
    }


}

my userentitydao interface is:

package org.intan.pedigree.dao;

import java.util.List;

import org.intan.pedigree.form.UserEntity;


public interface UserEntityDAO {
    public void removeUserEntity(Integer id);
    public List<UserEntity> listUserEntity() ;
    public void addUserEntity(UserEntity user) ;
    public void updateUserEntity(UserEntity user) ;
    public UserEntity getUserEntityByID(Integer id);
    public UserEntity findByName(String username);
}

and implementation is:

    @Repository
public class UserEntityDAOImpl implements UserEntityDAO{

    @Autowired
    private SessionFactory sessionFactory;

    public void addUserEntity(UserEntity user) {
        try {
        sessionFactory.getCurrentSession().save(user);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public UserEntity findByName(String username) {
        UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery(
                "select u form user u where u.username = '" + username + "'");
        return user;

    }

    public UserEntity getUserEntityByID(Integer id) {
        UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery(
                "select u form user u where id = '" + id + "'");
        return user;
    }
    public void updateUserEntity(UserEntity user) {
        try {
        sessionFactory.getCurrentSession().update(user);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public List<UserEntity> listUserEntity() {

        return sessionFactory.getCurrentSession().createQuery("from User")
                .list();
    }

    public void removeUserEntity(Integer id) {
        UserEntity user = (UserEntity) sessionFactory.getCurrentSession().load(
                UserEntity.class, id);
        if (null != user) {
            sessionFactory.getCurrentSession().delete(user);
        }

    }
}

now when i try to deploy on tomcat i get the following exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception
is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.intan.pedigree.dao.UserEntityDAO org.intan.pedigree.service.UserDetailsS
erviceImpl.dao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.intan.pedigree.dao.UserEntityDAO] found
 for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotatio
n.Autowired(required=true)}

and not mater what i do I can not figure out what is wrong with it. Any advice would be welcome.

thanks a lot

解决方案

I don't see any declaration for the UserEntityDAOImpl or Assembler beans in your context, and no component scanning to auto-detect it.

You either need to declare them alongside the UserDetailsServiceImpl, or add a <context:component-scan> somewhere.

这篇关于自定义用户信息的弹簧安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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