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> <artifactId>el-api</artifactId>
<version>2.2</version> <version>2.2</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.4.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- Spring Data JPA dependencies --> <!-- Spring Data JPA dependencies -->
<dependency> <dependency>

View File

@ -7,10 +7,8 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.ManyToMany; import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity @Entity
@Table
public class Privilege { public class Privilege {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)

View File

@ -9,19 +9,16 @@ import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.JoinTable; import javax.persistence.JoinTable;
import javax.persistence.ManyToMany; import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
@Entity @Entity
@Table
public class Role { public class Role {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@OneToMany(mappedBy = "role") @ManyToMany(mappedBy = "roles")
private Collection<User> users; private Collection<User> users;
@ManyToMany(cascade = CascadeType.ALL) @ManyToMany(cascade = CascadeType.ALL)

View File

@ -1,16 +1,18 @@
package org.baeldung.persistence.model; package org.baeldung.persistence.model;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.JoinTable;
import javax.persistence.Table; import javax.persistence.ManyToMany;
@Entity @Entity
@Table
public class User { public class User {
@Id @Id
@ -29,9 +31,12 @@ public class User {
private boolean tokenExpired; private boolean tokenExpired;
@ManyToOne(optional = false) @ManyToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "role_id") @JoinTable(
private Role role; name = "users_roles",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;
public User() { public User() {
super(); super();
@ -79,12 +84,12 @@ public class User {
this.password = password; this.password = password;
} }
public Role getRole() { public Collection<Role> getRoles() {
return role; return roles;
} }
public void setRole(Role role) { public void setRoles(Collection<Role> roles) {
this.role = role; this.roles = roles;
} }
public boolean isEnabled() { public boolean isEnabled() {

View File

@ -1,5 +1,7 @@
package org.baeldung.persistence.service; package org.baeldung.persistence.service;
import java.util.Arrays;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import org.baeldung.persistence.dao.RoleRepository; import org.baeldung.persistence.dao.RoleRepository;
@ -41,7 +43,7 @@ public class UserService implements IUserService {
user.setPassword(passwordEncoder.encode(accountDto.getPassword())); user.setPassword(passwordEncoder.encode(accountDto.getPassword()));
user.setEmail(accountDto.getEmail()); user.setEmail(accountDto.getEmail());
user.setRole(roleRepository.findByName("ROLE_USER")); user.setRoles(Arrays.asList(roleRepository.findByName("ROLE_USER")));
return repository.save(user); return repository.save(user);
} }

View File

@ -1,6 +1,7 @@
package org.baeldung.security; package org.baeldung.security;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -44,10 +45,10 @@ public class MyUserDetailsService implements UserDetailsService {
try { try {
final User user = userRepository.findByEmail(email); final User user = userRepository.findByEmail(email);
if (user == null) { 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) { } catch (final Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -55,13 +56,16 @@ public class MyUserDetailsService implements UserDetailsService {
// UTIL // UTIL
private final Collection<? extends GrantedAuthority> getAuthorities(final Role roleName) { private final Collection<? extends GrantedAuthority> getAuthorities(final Collection<Role> roles) {
return getGrantedAuthorities(getPrivileges(roleName)); 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 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) { for (final Privilege item : collection) {
privileges.add(item.getName()); 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.PrivilegeRepository;
import org.baeldung.persistence.dao.RoleRepository; import org.baeldung.persistence.dao.RoleRepository;
import org.baeldung.persistence.dao.UserRepository;
import org.baeldung.persistence.model.Privilege; import org.baeldung.persistence.model.Privilege;
import org.baeldung.persistence.model.Role; import org.baeldung.persistence.model.Role;
import org.baeldung.persistence.model.User;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent; 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.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -17,6 +21,9 @@ public class InitialDataLoader implements ApplicationListener<ContextRefreshedEv
boolean alreadyExist = false; boolean alreadyExist = false;
@Autowired
private UserRepository userRepository;
@Autowired @Autowired
private RoleRepository roleRepository; private RoleRepository roleRepository;
@ -28,33 +35,50 @@ public class InitialDataLoader implements ApplicationListener<ContextRefreshedEv
public void onApplicationEvent(final ContextRefreshedEvent event) { public void onApplicationEvent(final ContextRefreshedEvent event) {
if (alreadyExist) if (alreadyExist)
return; return;
if (roleRepository.count() > 0 || privilegeRepository.count() > 0)
return;
// == create initial privileges // == create initial privileges
final Privilege readPrivilege = new Privilege("READ_PRIVILEGE"); final Privilege readPrivilege = createPrivilegeIfNotFound("READ_PRIVILEGE");
final Privilege writePrivilege = new Privilege("WRITE_PRIVILEGE"); final Privilege writePrivilege = createPrivilegeIfNotFound("WRITE_PRIVILEGE");
privilegeRepository.save(readPrivilege);
privilegeRepository.save(writePrivilege);
// == create initial roles // == create initial roles
final Role admin = new Role("ROLE_ADMIN"); final Role admin = createRoleIfNotFound("ROLE_ADMIN");
final Role user = new Role("ROLE_USER"); final Role userRole = createRoleIfNotFound("ROLE_USER");
// == link roles and privileges // == link roles and privileges
admin.setPrivileges(Arrays.asList(readPrivilege, writePrivilege)); admin.setPrivileges(Arrays.asList(readPrivilege, writePrivilege));
user.setPrivileges(Arrays.asList(readPrivilege)); userRole.setPrivileges(Arrays.asList(readPrivilege));
roleRepository.save(admin); User user = new User();
roleRepository.save(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; alreadyExist = true;
} }
private final void createPrivilegeIfNotFound(final Privilege privilege) { @Transactional
if (privilegeRepository.findByName(privilege.getName()) != null) { private final Privilege createPrivilegeIfNotFound(String name) {
Privilege privilege = privilegeRepository.findByName(name);
if (privilege == null) {
privilege = new Privilege(name);
privilegeRepository.save(privilege); 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> <body>
<div class="container"> <div class="container">
<div class="span12"> <div class="span12">
<sec:authorize ifAnyGranted="READ_PRIVILEGE"> <sec:authorize ifNotGranted="WRITE_PRIVILEGE">
<spring:message code="message.unauth"></spring:message> <spring:message code="message.unauth"></spring:message>
</sec:authorize> </sec:authorize>
<sec:authorize ifAnyGranted="WRITE_PRIVILEGE"> <sec:authorize ifAnyGranted="WRITE_PRIVILEGE">