首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring,Spring,Security集成

Spring,Spring,Security集成
EN

Stack Overflow用户
提问于 2014-05-14 12:33:06
回答 1查看 1.5K关注 0票数 1

我有一个Spring应用程序,它使用JPA和Hibernate将对象映射到MySQL数据库。我增加了Security,并让它使用内存中的模型。我希望添加用户和角色实体,以便与Security集成。

我在想,是否有人能为我指明如何做这件事的方向,或者任何关于如何做到这一点的教程?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-14 13:36:37

实现一个加载用户和Rolemodel的UserDetailsService。它只是返回一个loadUserByUsername对象的UserDetails。UserDetails本身将包含所有角色的列表。这里有一个叫做GrantedAuthority的角色。有一个SimpleGrantedAuthority来从一个简单的Rolename (字符串)创建它。

但是也许JdbcDaoImpl已经满足了你的需求。

在评论中更新适当的问题:

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

示例:降到最低。

角色

代码语言:javascript
复制
@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;
}

用户

代码语言:javascript
复制
@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;
   }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23654889

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档