【问题标题】:Spring MVC, Spring Data JPA, Spring Security integrationSpring MVC、Spring Data JPA、Spring Security 集成
【发布时间】:2014-07-02 12:32:22
【问题描述】:

我有一个 Spring MVC Web 应用程序,它使用 JPA 和 Hibernate 将对象映射到 MySQL 数据库。我已经添加了 Spring Security 并让它在使用内存模型方面工作。我想添加用户和角色实体以与 Spring Security 集成。

我想知道是否有人可以指出如何执行此操作的方向或有关如何完成此操作的任何教程?

【问题讨论】:

    标签: java spring-mvc jpa spring-security


    【解决方案1】:

    实现一个UserDetailsService 来加载您的用户和角色模型。它只是将返回 UserDetails 对象的 loadUserByUsername。 UserDetails 本身将包含所有角色的列表。一个角色在这里称为 GrantedAuthority。有一个 SimpleGrantedAuthority 可以从一个简单的角色名(字符串)创建它。

    但也许JdbcDaoImpl 足以满足您的需求。

    在评论中更新到期问题:

    只需像往常一样设计您的用户角色关系。在您的 UserDetails 实现中,您需要将 getAuthorities 中的角色作为 GrantedAuthority 返回。

    示例: 减少到最低限度。

    角色

    @Entity(name = "auth_role")
    public class Role {
    
      @Id
      @Column
      private String id;
    
      @Column(nullable = false, unique = true)
      /**
       *unique and transformed to GrantedAuthority,can be used in Spring expression hasRole, etc
      **/
      private String name;
    
    
      @Column(nullable = true)
      private String description;
    }
    

    用户

    @Entity(name = "auth_user")
    public class User implements UserDetails {
    
       @Id
       @Column
       private String id;
    
       @Column(nullable = false, unique = true)
       private String name;
    
    
       @ManyToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
       /** 
        * relation to our roles
       **/
       private Set<Role> roles = new HashSet<Role>();
    
       /**
       * implements getAuthorities and transformes our Roles using the unique names to 
       * SimpleGrantedAuthority
       **/
       public Collection<? extends GrantedAuthority> getAuthorities() {
         Set<GrantedAuthority> authList = new HashSet<GrantedAuthority>();
    
         for (Role role : user.getRoles()) {
           authList.add(new SimpleGrantedAuthority(role.getName()));
         }        
    
         // Return list of granted authorities
         return authList;
       }
    }
    

    【讨论】:

    • 谢谢,我试试看。我想将其他实体映射到我的用户实体,所以我可能需要使用第一种方法。
    • 如果它解决了你的问题,你可以接受我的回答。或者帮助我改进它。谢谢。
    • 您好,您能不能给我提供一个代码示例或者指点我的方向。
    • 我已经实现了 UserDetailsS​​ervice 并创建了一个扩展 UserDetails 的用户实体。如何向我的用户实体添加角色?
    • 感谢您的帮助,我实际上已经完成了这项工作,我会接受您的回答。
    猜你喜欢
    • 2017-09-22
    • 2023-01-30
    • 2013-01-11
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2014-10-24
    相关资源
    最近更新 更多