我有一个Spring应用程序,它使用JPA和Hibernate将对象映射到MySQL数据库。我增加了Security,并让它使用内存中的模型。我希望添加用户和角色实体,以便与Security集成。
我在想,是否有人能为我指明如何做这件事的方向,或者任何关于如何做到这一点的教程?
发布于 2014-05-14 13:36:37
实现一个加载用户和Rolemodel的UserDetailsService。它只是返回一个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;
}
}https://stackoverflow.com/questions/23654889
复制相似问题