add spring security roles and privileges

This commit is contained in:
DOHA 2015-01-08 20:02:04 +02:00
parent f924f8be61
commit 2937fca5cd
12 changed files with 234 additions and 59 deletions

View File

@ -0,0 +1,8 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.Privilege;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PrivilegeRepository extends JpaRepository<Privilege, Long> {
public Privilege findByName(String name);
}

View File

@ -0,0 +1,8 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, Long> {
public Role findByName(String name);
}

View File

@ -0,0 +1,85 @@
package org.baeldung.persistence.model;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table
public class Privilege {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany(mappedBy = "privileges")
private Collection<Role> roles;
public Privilege() {
super();
}
public Privilege(String name) {
super();
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Privilege privilege = (Privilege) obj;
if (!privilege.equals(privilege.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Privilege [name=").append(name).append("]").append("[id=").append(id).append("]");
return builder.toString();
}
}

View File

@ -1,14 +1,17 @@
package org.baeldung.persistence.model;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.JoinColumn;
@Entity
@Table
@ -18,25 +21,22 @@ public class Role {
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
@OneToMany(mappedBy = "role")
private Collection<User> users;
private Integer role;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "roles_privileges", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id"))
private Collection<Privilege> privileges;
private String name;
public Role() {
super();
}
public Role(Integer role) {
public Role(String name) {
super();
this.role = role;
}
public Role(Integer role, User user) {
super();
this.role = role;
this.user = user;
this.name = name;
}
public Long getId() {
@ -47,27 +47,35 @@ public class Role {
this.id = id;
}
public User getUser() {
return user;
public String getName() {
return name;
}
public void setUser(User user) {
this.user = user;
public void setName(String name) {
this.name = name;
}
public Integer getRole() {
return role;
public Collection<User> getUsers() {
return users;
}
public void setRole(Integer role) {
this.role = role;
public void setUsers(Collection<User> users) {
this.users = users;
}
public Collection<Privilege> getPrivileges() {
return privileges;
}
public void setPrivileges(Collection<Privilege> privileges) {
this.privileges = privileges;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((role == null) ? 0 : role.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@ -80,7 +88,7 @@ public class Role {
if (getClass() != obj.getClass())
return false;
final Role role = (Role) obj;
if (!role.equals(role.role))
if (!role.equals(role.name))
return false;
return true;
}
@ -88,7 +96,7 @@ public class Role {
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Role [role=").append(role).append("]").append("[id=").append(id).append("]");
builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]");
return builder.toString();
}
}

View File

@ -1,16 +1,16 @@
package org.baeldung.persistence.model;
import javax.persistence.CascadeType;
//ERASE
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table
public class User {
@Id
@ -29,7 +29,8 @@ public class User {
private boolean tokenExpired;
@OneToOne(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@ManyToOne(optional = false)
@JoinColumn(name = "role_id")
private Role role;
public User() {

View File

@ -2,9 +2,9 @@ package org.baeldung.persistence.service;
import javax.transaction.Transactional;
import org.baeldung.persistence.dao.RoleRepository;
import org.baeldung.persistence.dao.UserRepository;
import org.baeldung.persistence.dao.VerificationTokenRepository;
import org.baeldung.persistence.model.Role;
import org.baeldung.persistence.model.User;
import org.baeldung.persistence.model.VerificationToken;
import org.baeldung.validation.EmailExistsException;
@ -24,6 +24,9 @@ public class UserService implements IUserService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private RoleRepository roleRepository;
// API
@Override
@ -38,7 +41,7 @@ public class UserService implements IUserService {
user.setPassword(passwordEncoder.encode(accountDto.getPassword()));
user.setEmail(accountDto.getEmail());
user.setRole(new Role(Integer.valueOf(1), user));
user.setRole(roleRepository.findByName("ROLE_USER"));
return repository.save(user);
}

View File

@ -48,11 +48,11 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
if (grantedAuthority.getAuthority().equals("READ_PRIVILEGE")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
} else if (grantedAuthority.getAuthority().equals("WRITE_PRIVILEGE")) {
isAdmin = true;
isUser = false;
break;
}
}

View File

@ -7,7 +7,10 @@ import java.util.List;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.baeldung.persistence.dao.RoleRepository;
import org.baeldung.persistence.dao.UserRepository;
import org.baeldung.persistence.model.Privilege;
import org.baeldung.persistence.model.Role;
import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
@ -27,6 +30,8 @@ public class MyUserDetailsService implements UserDetailsService {
private IUserService service;
@Autowired
private MessageSource messages;
@Autowired
private RoleRepository roleRepository;
public MyUserDetailsService() {
@ -40,34 +45,33 @@ public class MyUserDetailsService implements UserDetailsService {
try {
User user = userRepository.findByEmail(email);
if (user == null) {
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(new Integer(1)));
return new org.springframework.security.core.userdetails.User(" ", " ", enabled, true, true, true, getAuthorities(roleRepository.findByName("ROLE_USER")));
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole().getRole()));
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getRole()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
private Collection<? extends GrantedAuthority> getAuthorities(Role roleName) {
List<GrantedAuthority> authList = getGrantedAuthorities(getPrivileges(roleName));
return authList;
}
public List<String> getRoles(Integer role) {
List<String> roles = new ArrayList<String>();
if (role.intValue() == 2) {
roles.add("ROLE_ADMIN");
} else if (role.intValue() == 1) {
roles.add("ROLE_USER");
public List<String> getPrivileges(Role role) {
List<String> privileges = new ArrayList<String>();
Collection<Privilege> collection = role.getPrivileges();
for (Privilege item : collection) {
privileges.add(item.getName());
}
return roles;
return privileges;
}
private static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
private static List<GrantedAuthority> getGrantedAuthorities(List<String> privileges) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
for (String privilege : privileges) {
authorities.add(new SimpleGrantedAuthority(privilege));
}
return authorities;
}

View File

@ -0,0 +1,58 @@
package org.baeldung.spring;
import java.util.Arrays;
import org.baeldung.persistence.dao.PrivilegeRepository;
import org.baeldung.persistence.dao.RoleRepository;
import org.baeldung.persistence.model.Privilege;
import org.baeldung.persistence.model.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class InitialDataLoader implements ApplicationListener<ContextRefreshedEvent>{
boolean alreadyExist = false;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PrivilegeRepository privilegeRepository;
@Override
@Transactional
public void onApplicationEvent(ContextRefreshedEvent event) {
if(alreadyExist)
return;
if(roleRepository.findAll().size() > 0 || privilegeRepository.findAll().size() > 0)
return;
//== create initial roles
Role admin = new Role("ROLE_ADMIN");
Role user = new Role("ROLE_USER");
//== create initial privileges
Privilege readPrivilege = new Privilege("READ_PRIVILEGE");
Privilege writePrivilege = new Privilege("WRITE_PRIVILEGE");
//== link roles and privileges
Privilege[] adminPrivileges = {readPrivilege, writePrivilege};
admin.setPrivileges(Arrays.asList(adminPrivileges));
Privilege[] userPrivileges = {readPrivilege};
user.setPrivileges(Arrays.asList(userPrivileges));
//== save to database
privilegeRepository.save(readPrivilege);
privilegeRepository.save(writePrivilege);
roleRepository.save(admin);
roleRepository.save(user);
alreadyExist = true;
}
}

View File

@ -11,10 +11,10 @@
<body>
<div class="container">
<div class="span12">
<sec:authorize ifAnyGranted="ROLE_USER">
<sec:authorize ifAnyGranted="READ_PRIVILEGE">
<spring:message code="message.unauth"></spring:message>
</sec:authorize>
<sec:authorize ifAnyGranted="ROLE_ADMIN">
<sec:authorize ifAnyGranted="WRITE_PRIVILEGE">
<H1>
<spring:message code="label.pages.admin.message"></spring:message>
</H1>

View File

@ -10,11 +10,11 @@
<div class="container">
<div class="span12">
<h1>This is the landing page for the admin</h1>
<sec:authorize access="hasRole('ROLE_USER')">
<sec:authorize access="hasRole('READ_PRIVILEGE')">
This text is only visible to a user
<br />
</sec:authorize>
<sec:authorize access="hasRole('ROLE_ADMIN')">
<sec:authorize access="hasRole('WRITE_PRIVILEGE')">
This text is only visible to an admin
<br />
</sec:authorize>

View File

@ -13,12 +13,12 @@
<div class="container">
<div class="span12">
<sec:authorize access="hasRole('ROLE_USER')">
<sec:authorize access="hasRole('READ_PRIVILEGE')">
<spring:message code="label.pages.user.message"></spring:message>
<br />
</sec:authorize>
<sec:authorize access="hasRole('ROLE_ADMIN')">
<sec:authorize access="hasRole('WRITE_PRIVILEGE')">
<spring:message code="label.pages.admin.message"></spring:message>
<br />
</sec:authorize>