当前位置: 首页 > 面试题库 >

带有自定义用户详细信息的Spring Security

终安和
2023-03-14
问题内容

我正在尝试使用数据库表在Spring应用程序中应用安全性。

到目前为止,我的applicationContext-Security中有:

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

我对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.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);
    }
}

我的汇编程序如下所示:

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

现在,用户实体为:

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


}

我的userentitydao界面是:

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

实现是:

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

    }
}

现在,当我尝试在tomcat上进行部署时,出现以下异常:

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

而不管我该怎么办,我不知道这是怎么回事。任何的建议都受欢迎。

非常感谢


问题答案:

在您的上下文中,我看不到任何关于UserEntityDAOImpl或的声明Assembler,也没有组件扫描来自动检测到它。

您需要在旁边声明它们UserDetailsServiceImpl,或在<context:component-scan>某处添加一个。



 类似资料:
  • 我对Java和Spring3(过去8年主要使用PHP)还很陌生。我已经使用spring security 3来处理所有默认的userDetails和userDetailsService,我知道我可以通过使用以下命令访问控制器中登录用户的用户名: 但有两个问题我想不通: > 我希望在用户登录时存储许多其他用户详细信息(如DOB、性别等),并在以后通过控制器进行访问。我需要做什么才能使创建的userD

  • 我正在使用spring security 3.2、JSF2和Hibernate4。 我已经完成了3/4的工作:)但是我的身份验证系统还不起作用。 我有一个实现UserDetailsService的UserService,一个实现UserDetails的域类用户。 登录系统从不阻止用户访问安全页面,我尝试了数据库中不存在的用户名和密码... 谢谢你的帮助。 我有一个loginBean,当用户通过登录

  • 我有一个富网络(基于反应)前端应用程序,它将请求发送到后端资源服务器应用程序。请求在头中与JWT一起发送以进行身份验证。我的设置对Okta授权服务器进行身份验证,并从单独的服务中检索组/授权。 我将后端服务器设置为Springboot应用程序,带有Spring Security Oauth2资源服务器 有了这个设置,我可以使用JwkTokenStore实现来验证JWT令牌(它在内部使用JwkVer

  • 同时尝试Spring启动、安全性和数据。 我刚刚遇到了这种情况: 我在内存数据库中使用H2,并在启动时用liquibase和一个用户用用户名和密码对其进行加密。 现在我想让Spring Security性根据H2进行身份验证。为此,我有以下代码: 并且我实现了如下userDetails: 但我的测试一直失败 身份验证不应为空 尝试登录会给我 凭据错误 要使UserDetailsService的自定

  • 我试图在Typescript中设置一个节点gRPC服务器,我已经让一切正常,但处理请求/响应的冗长让我感觉不好。我遵循了https://github.com/blokur/grpc-ts-demo这似乎是许多示例项目的设置方式。 处理请求或响应时会出现问题,而创建的代码生成工具()存根要求您处理如下请求和响应: 从为生成的类型为: 因此,如果消息有一堆字段,或者如果您必须编写一堆RPC处理程序,那

  • 我有一个Keycloak连接器,它允许我通过SSO检索用户的用户名。我想使用这个用户名来认证用户,并在数据库中查找他的权限,并将这个用户权限注入到spring security中,以便能够使用它的功能。 我用自定义的UserDetailsService创建了一个自定义的authenticationProvider,但我一直面临的问题是,我每次都被重定向到spring security登录页面。我认