简体   繁体   English

Spring MVC,Spring Data JPA,Spring Security集成

[英]Spring MVC, Spring Data JPA, Spring Security integration

I have a Spring MVC web app which uses JPA and Hibernate to map objects to a MySQL database. 我有一个Spring MVC Web应用程序,它使用JPA和Hibernate将对象映射到MySQL数据库。 I have added Spring Security and have it working so far as using an in memory model. 我已经添加了Spring Security,并使其能够使用内存模型。 I want to add user and role entities to integrate with Spring Security. 我想添加用户和角色实体以与Spring Security集成。

I was wondering if someone could point me in the direction of how to do this or any tutorials on how to accomplish this? 我想知道是否有人可以指出我的方向或有关如何实现此目标的任何教程?

Implement an UserDetailsService which loads your User- and Rolemodel. 实现一个UserDetailsS​​ervice来加载您的用户模型和角色模型。 Its just the loadUserByUsername which will return a UserDetails Object. 它只是loadUserByUsername,它将返回一个UserDetails对象。 The UserDetails itself will have a list of all roles. UserDetails本身将具有所有角色的列表。 A role is here called know as GrantedAuthority. 在这里,一个角色称为GrantedAuthority。 Theres a SimpleGrantedAuthority to create it from a simple Rolename (String). 有一个SimpleGrantedAuthority可以从一个简单的Rolename(字符串)创建它。

But maybe JdbcDaoImpl is enough for your needs. 但是,也许JdbcDaoImpl足以满足您的需求。

Update due question in comment: 更新评论中的适当问题:

Just design your User Role relation as you would normally do. 只需像通常那样设计用户角色关系即可。 In your UserDetails Implementation you need to return your roles in getAuthorities as GrantedAuthority. 在您的UserDetails实现中,您需要将getAuthorities中的角色作为GrantedAuthority返回。

Example: reduced to the minimum. 示例:减少到最小。

Role 角色

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

User 用户

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM