代码之家  ›  专栏  ›  技术社区  ›  Ta Sas

如何用Hibernate/JPA2实现Spring安全用户/权限?

  •  7
  • Ta Sas  · 技术社区  · 16 年前

    我尝试在Hibernate/JPA2中实现DAOs来使用Spring安全数据库身份验证。Spring使用以下关系和关联来表示用户角色:

    alt text

    表示为postgresql创建查询:

    CREATE TABLE users
    (
      username character varying(50) NOT NULL,
      "password" character varying(50) NOT NULL,
      enabled boolean NOT NULL,
      CONSTRAINT users_pkey PRIMARY KEY (username)
    );
    CREATE TABLE authorities
    (
      username character varying(50) NOT NULL,
      authority character varying(50) NOT NULL,
      CONSTRAINT fk_authorities_users FOREIGN KEY (username)
          REFERENCES users (username) MATCH SIMPLE
          ON UPDATE NO ACTION ON DELETE NO ACTION
    );
    

    GrantedAuthorities , UserDetailsService UserDetailsmanager ,一切都很好。但是,我对Spring的JDBC实现并不满意,我想自己写一个。为此,我尝试通过以下业务对象创建关系的表示:

    用户实体:

    @Entity
    @Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = {"username"})})
    public class AppUser implements UserDetails, CredentialsContainer {
    
        private static final long serialVersionUID = -8275492272371421013L;
    
        @Id
        @Column(name = "username", nullable = false, unique = true)
        private String username;
    
        @Column(name = "password", nullable = false)
        @NotNull
        private String password;
    
        @OneToMany(
                fetch = FetchType.EAGER, cascade = CascadeType.ALL,
                mappedBy = "appUser"
        )
        private Set<AppAuthority> appAuthorities;
    
        @Column(name = "accountNonExpired")
        private Boolean accountNonExpired;
    
        @Column(name = "accountNonLocked")
        private Boolean accountNonLocked;
    
        @Column(name = "credentialsNonExpired")
        private Boolean credentialsNonExpired;
    
        @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
        @JoinColumn(name = "personalinformation_fk", nullable = true)
        @JsonIgnore
        private PersonalInformation personalInformation;
    
        @Column(name = "enabled", nullable = false)
        @NotNull
        private Boolean enabled;
    
        public AppUser(
                String username,
                String password,
                boolean enabled,
                boolean accountNonExpired,
                boolean credentialsNonExpired,
                boolean accountNonLocked,
                Collection<? extends AppAuthority> authorities,
                PersonalInformation personalInformation
        ) {
            if (((username == null) || "".equals(username)) || (password == null)) {
                throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
            }
    
            this.username = username;
            this.password = password;
            this.enabled = enabled;
            this.accountNonExpired = accountNonExpired;
            this.credentialsNonExpired = credentialsNonExpired;
            this.accountNonLocked = accountNonLocked;
            this.appAuthorities = Collections.unmodifiableSet(sortAuthorities(authorities));
            this.personalInformation = personalInformation;
        }
    
        public AppUser() {
        }
    
        @JsonIgnore
        public PersonalInformation getPersonalInformation() {
            return personalInformation;
        }
    
        @JsonIgnore
        public void setPersonalInformation(PersonalInformation personalInformation) {
            this.personalInformation = personalInformation;
        }
    
        // Getters, setters 'n other stuff
    

    以及作为授权机构实施的机构实体:

    @Entity
    @Table(name = "authorities", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
    public class AppAuthority implements GrantedAuthority, Serializable {
        //~ Instance fields ================================================================================================
    
        private static final long serialVersionUID = 1L;
    
        @Id
        @GeneratedValue(strategy = GenerationType.TABLE)
        @Column(name = "id", nullable = false)
        private Integer id;
    
        @Column(name = "username", nullable = false)
        private String username;
    
        @Column(name = "authority", nullable = false)
        private String authority;
    
        // Here comes the buggy attribute. It is supposed to repesent the
        // association username<->username, but I just don't know how to
        // implement it 
        @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
        @JoinColumn(name = "appuser_fk")
        private AppUser appUser;
    
        //~ Constructors ===================================================================================================
    
        public AppAuthority(String username, String authority) {
            Assert.hasText(authority,
                    "A granted authority textual representation is required");
            this.username = username;
            this.authority = authority;
        }
    
        public AppAuthority() {
        }
    
        // Getters 'n setters 'n other stuff
    

    我的问题是 @ManyToOne 协会 AppAuthorities String ... 而Hibernate需要关联的实体。所以我尝试的实际上是提供正确的实体并通过 @JoinColumn(name = "appuser_fk") . 当然,这是垃圾,因为为了加载用户,我将在 username appuser_fk ,将始终为空。

    所以我的问题是:关于如何修改上述代码以获得数据模型的正确JPA2实现,有什么建议吗?

    谢谢

    3 回复  |  直到 16 年前
        1
  •  8
  •   axtavt    16 年前

    你呢 AppAuthority 不需要 username 完全。Spring Security不能依赖于它,因为它依赖于 GrantedAuthority interface

    但更好的做法是将域模型与Spring安全性分离。当你有一个习惯 UserDetailsService ,您不需要模拟springsecurity的默认数据库模式或其对象模型。你的 你可以自己装 AppUser 和 骇人听闻 UserDetails 和 这是基于他们的。这将导致更干净的设计和更好的关注点分离。

        2
  •  0
  •   Stephen C    16 年前

    这看起来像是使用特定于域的密钥的典型Hibernate问题。一个可能的解决方法是创建一个新的主键字段;例如。 userId int 对于 Users 和 Authorities Authorities.userName Users.userName 到唯一的次键。

        3
  •  0
  •   Kumar Sambhav    13 年前

    在conf中定义userDetailsService时,您可以根据需要对用户和权限类建模并使用它外形:-

    <sec:jdbc-user-service data-source-ref="webDS"
                    id="userDetailsService"
                    users-by-username-query="SELECT USER_NAME,PASSWORD,TRUE FROM CUSTOMER WHERE USER_NAME=?"
                    authorities-by-username-query="SELECT c.USER_NAME,r.ROLE_NAME from CUSTOMER c 
                                              JOIN CUSTOMER_ROLE cr ON c.CUSTOMER_ID = cr.CUSTOMER_ID 
                                              JOIN ROLE r ON cr.ROLE_ID = r.ROLE_ID 
                                              WHERE USER_NAME=?" />