Merge pull request #112 from Doha2012/master

Modify spring security roles
This commit is contained in:
Eugen 2015-01-09 20:51:50 +02:00
commit 6af6b01ab5
9 changed files with 165 additions and 37 deletions

View File

@ -59,6 +59,13 @@
<artifactId>el-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.4.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- Spring Data JPA dependencies -->
<dependency>

View File

@ -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)

View File

@ -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<User> users;
@ManyToMany(cascade = CascadeType.ALL)

View File

@ -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<Role> roles;
public User() {
super();
@ -79,12 +84,12 @@ public class User {
this.password = password;
}
public Role getRole() {
return role;
public Collection<Role> getRoles() {
return roles;
}
public void setRole(Role role) {
this.role = role;
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
public boolean isEnabled() {

View File

@ -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);
}

View File

@ -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<? extends GrantedAuthority> getAuthorities(final Role roleName) {
return getGrantedAuthorities(getPrivileges(roleName));
private final Collection<? extends GrantedAuthority> getAuthorities(final Collection<Role> roles) {
return getGrantedAuthorities(getPrivileges(roles));
}
private final List<String> getPrivileges(final Role role) {
private final List<String> getPrivileges(final Collection<Role> roles) {
final List<String> privileges = new ArrayList<String>();
final Collection<Privilege> collection = role.getPrivileges();
final List<Privilege> collection = new ArrayList<Privilege>();
for (Role role : roles) {
collection.addAll(role.getPrivileges());
}
for (final Privilege item : collection) {
privileges.add(item.getName());
}

View File

@ -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<ContextRefreshedEv
boolean alreadyExist = false;
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@ -28,33 +35,50 @@ public class InitialDataLoader implements ApplicationListener<ContextRefreshedEv
public void onApplicationEvent(final ContextRefreshedEvent event) {
if (alreadyExist)
return;
if (roleRepository.count() > 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;
}
}

View File

@ -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()));
}
}

View File

@ -11,7 +11,7 @@
<body>
<div class="container">
<div class="span12">
<sec:authorize ifAnyGranted="READ_PRIVILEGE">
<sec:authorize ifNotGranted="WRITE_PRIVILEGE">
<spring:message code="message.unauth"></spring:message>
</sec:authorize>
<sec:authorize ifAnyGranted="WRITE_PRIVILEGE">