From c8513d0d80595a675438921671e452f97d626f9b Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 9 Jan 2015 10:56:02 +0200 Subject: [PATCH] Modify spring security roles --- .../pom.xml | 7 ++ .../baeldung/persistence/model/Privilege.java | 2 - .../org/baeldung/persistence/model/Role.java | 5 +- .../org/baeldung/persistence/model/User.java | 25 +++-- .../persistence/service/UserService.java | 4 +- .../security/MyUserDetailsService.java | 16 ++-- .../baeldung/spring/InitialDataLoader.java | 50 +++++++--- .../test/SpringSecurityRolesTest.java | 91 +++++++++++++++++++ .../src/main/webapp/WEB-INF/view/admin.jsp | 2 +- 9 files changed, 165 insertions(+), 37 deletions(-) create mode 100644 spring-security-login-and-registration/src/main/java/org/baeldung/test/SpringSecurityRolesTest.java diff --git a/spring-security-login-and-registration/pom.xml b/spring-security-login-and-registration/pom.xml index 8b3a0da99a..124f307dd3 100644 --- a/spring-security-login-and-registration/pom.xml +++ b/spring-security-login-and-registration/pom.xml @@ -59,6 +59,13 @@ el-api 2.2 + + + org.springframework + spring-test + 4.1.4.RELEASE + test + diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Privilege.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Privilege.java index b8b1266aff..c403ffb7a2 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Privilege.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Privilege.java @@ -7,10 +7,8 @@ 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) diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java index 9bea890ff5..01851776dd 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/Role.java @@ -9,19 +9,16 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; import javax.persistence.JoinColumn; @Entity -@Table public class Role { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @OneToMany(mappedBy = "role") + @ManyToMany(mappedBy = "roles") private Collection users; @ManyToMany(cascade = CascadeType.ALL) diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java index 881b5dd988..44d2d1426a 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java @@ -1,16 +1,18 @@ package org.baeldung.persistence.model; +import java.util.Collection; + +import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; @Entity -@Table public class User { @Id @@ -29,9 +31,12 @@ public class User { private boolean tokenExpired; - @ManyToOne(optional = false) - @JoinColumn(name = "role_id") - private Role role; + @ManyToMany(cascade = CascadeType.ALL) + @JoinTable( + name = "users_roles", + joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) + private Collection roles; public User() { super(); @@ -79,12 +84,12 @@ public class User { this.password = password; } - public Role getRole() { - return role; + public Collection getRoles() { + return roles; } - public void setRole(Role role) { - this.role = role; + public void setRoles(Collection roles) { + this.roles = roles; } public boolean isEnabled() { diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserService.java index ab1a728b12..15989f9e8b 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/persistence/service/UserService.java @@ -1,5 +1,7 @@ package org.baeldung.persistence.service; +import java.util.Arrays; + import javax.transaction.Transactional; import org.baeldung.persistence.dao.RoleRepository; @@ -41,7 +43,7 @@ public class UserService implements IUserService { user.setPassword(passwordEncoder.encode(accountDto.getPassword())); user.setEmail(accountDto.getEmail()); - user.setRole(roleRepository.findByName("ROLE_USER")); + user.setRoles(Arrays.asList(roleRepository.findByName("ROLE_USER"))); return repository.save(user); } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java index a892e1e5e8..da5e0af894 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -1,6 +1,7 @@ package org.baeldung.security; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -44,10 +45,10 @@ public class MyUserDetailsService implements UserDetailsService { try { final User user = userRepository.findByEmail(email); if (user == null) { - return new org.springframework.security.core.userdetails.User(" ", " ", true, true, true, true, getAuthorities(roleRepository.findByName("ROLE_USER"))); + return new org.springframework.security.core.userdetails.User(" ", " ", true, true, true, true, getAuthorities(Arrays.asList(roleRepository.findByName("ROLE_USER")))); } - return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRole())); + return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRoles())); } catch (final Exception e) { throw new RuntimeException(e); } @@ -55,13 +56,16 @@ public class MyUserDetailsService implements UserDetailsService { // UTIL - private final Collection getAuthorities(final Role roleName) { - return getGrantedAuthorities(getPrivileges(roleName)); + private final Collection getAuthorities(final Collection roles) { + return getGrantedAuthorities(getPrivileges(roles)); } - private final List getPrivileges(final Role role) { + private final List getPrivileges(final Collection roles) { final List privileges = new ArrayList(); - final Collection collection = role.getPrivileges(); + final List collection = new ArrayList(); + for (Role role : roles) { + collection.addAll(role.getPrivileges()); + } for (final Privilege item : collection) { privileges.add(item.getName()); } diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/InitialDataLoader.java b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/InitialDataLoader.java index ebd9290c34..0cc14f5321 100644 --- a/spring-security-login-and-registration/src/main/java/org/baeldung/spring/InitialDataLoader.java +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/spring/InitialDataLoader.java @@ -4,11 +4,15 @@ import java.util.Arrays; import org.baeldung.persistence.dao.PrivilegeRepository; 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.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -17,6 +21,9 @@ public class InitialDataLoader implements ApplicationListener 0 || privilegeRepository.count() > 0) - return; // == create initial privileges - final Privilege readPrivilege = new Privilege("READ_PRIVILEGE"); - final Privilege writePrivilege = new Privilege("WRITE_PRIVILEGE"); - privilegeRepository.save(readPrivilege); - privilegeRepository.save(writePrivilege); + final Privilege readPrivilege = createPrivilegeIfNotFound("READ_PRIVILEGE"); + final Privilege writePrivilege = createPrivilegeIfNotFound("WRITE_PRIVILEGE"); // == create initial roles - final Role admin = new Role("ROLE_ADMIN"); - final Role user = new Role("ROLE_USER"); + final Role admin = createRoleIfNotFound("ROLE_ADMIN"); + final Role userRole = createRoleIfNotFound("ROLE_USER"); // == link roles and privileges admin.setPrivileges(Arrays.asList(readPrivilege, writePrivilege)); - user.setPrivileges(Arrays.asList(readPrivilege)); + userRole.setPrivileges(Arrays.asList(readPrivilege)); - roleRepository.save(admin); - roleRepository.save(user); + User user = new User(); + user.setFirstName("Test"); + user.setLastName("Test"); + PasswordEncoder encoder = new BCryptPasswordEncoder(); + user.setPassword(encoder.encode("test")); + user.setEmail("test@test.com"); + user.setRoles(Arrays.asList(admin)); + user.setEnabled(true); + userRepository.save(user); alreadyExist = true; } - private final void createPrivilegeIfNotFound(final Privilege privilege) { - if (privilegeRepository.findByName(privilege.getName()) != null) { + @Transactional + private final Privilege createPrivilegeIfNotFound(String name) { + Privilege privilege = privilegeRepository.findByName(name); + if (privilege == null) { + privilege = new Privilege(name); privilegeRepository.save(privilege); } + return privilege; + } + + @Transactional + private final Role createRoleIfNotFound(String name) { + Role role = roleRepository.findByName(name); + if (role == null) { + role = new Role(name); + roleRepository.save(role); + } + return role; } } \ No newline at end of file diff --git a/spring-security-login-and-registration/src/main/java/org/baeldung/test/SpringSecurityRolesTest.java b/spring-security-login-and-registration/src/main/java/org/baeldung/test/SpringSecurityRolesTest.java new file mode 100644 index 0000000000..1187635d08 --- /dev/null +++ b/spring-security-login-and-registration/src/main/java/org/baeldung/test/SpringSecurityRolesTest.java @@ -0,0 +1,91 @@ +package org.baeldung.test; + +import java.util.Arrays; + +import org.baeldung.persistence.dao.PrivilegeRepository; +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.spring.AppConfig; +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.PersistenceJPAConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.transaction.TransactionConfiguration; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppConfig.class, MvcConfig.class, PersistenceJPAConfig.class, SecSecurityConfig.class}) +public class SpringSecurityRolesTest { + + @Autowired + private UserRepository userRepository; + + @Autowired + private RoleRepository roleRepository; + + @Autowired + private PrivilegeRepository privilegeRepository; + + private User user; + private Role role; + private Privilege privilege; + + @Before + public void init(){ + privilege = new Privilege("TEST_PRIVILEGE"); + privilegeRepository.save(privilege); + + role = new Role("TEST_ROLE"); + roleRepository.save(role); + + user = new User(); + user.setFirstName("John"); + user.setLastName("Doe"); + PasswordEncoder encoder = new BCryptPasswordEncoder(); + user.setPassword(encoder.encode("123")); + user.setEmail("john@doe.com"); + user.setRoles(Arrays.asList(role)); + user.setEnabled(true); + userRepository.save(user); + } + + @After + public void cleanUp(){ + privilegeRepository.delete(privilege); + roleRepository.delete(role); + userRepository.delete(user); + } + + @Test + public void testDeleteUser(){ + userRepository.delete(user); + System.out.println(roleRepository.findByName(role.getName())); + } + + @Test + public void testDeleteRole(){ + roleRepository.delete(role); + System.out.println(privilegeRepository.findByName(privilege.getName())); + System.out.println(userRepository.findByEmail(user.getEmail())); + } + + @Test + public void testDeletePrivilege(){ + privilegeRepository.delete(privilege); + System.out.println(roleRepository.findByName(role.getName())); + } +} diff --git a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp index a5d9c0e765..b31fbaef45 100644 --- a/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp +++ b/spring-security-login-and-registration/src/main/webapp/WEB-INF/view/admin.jsp @@ -11,7 +11,7 @@
- +