簡體   English   中英

Spring MVC,Spring Data JPA,Spring Security集成

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

我有一個Spring MVC Web應用程序,它使用JPA和Hibernate將對象映射到MySQL數據庫。 我已經添加了Spring Security,並使其能夠使用內存模型。 我想添加用戶和角色實體以與Spring Security集成。

我想知道是否有人可以指出我的方向或有關如何實現此目標的任何教程?

實現一個UserDetailsS​​ervice來加載您的用戶模型和角色模型。 它只是loadUserByUsername,它將返回一個UserDetails對象。 UserDetails本身將具有所有角色的列表。 在這里,一個角色稱為GrantedAuthority。 有一個SimpleGrantedAuthority可以從一個簡單的Rolename(字符串)創建它。

但是,也許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;
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM