Pregunta

I have a Spring MVC web app which uses JPA and Hibernate to map objects to a MySQL database. I have added Spring Security and have it working so far as using an in memory model. I want to add user and role entities to integrate with 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?

¿Fue útil?

Solución

Implement an UserDetailsService which loads your User- and Rolemodel. Its just the loadUserByUsername which will return a UserDetails Object. The UserDetails itself will have a list of all roles. A role is here called know as GrantedAuthority. Theres a SimpleGrantedAuthority to create it from a simple Rolename (String).

But maybe JdbcDaoImpl is enough for your needs.

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.

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;
   }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top