Merge pull request #3241 from linhvovn/BAEL-1411

[tlinh2110@gmail.com] Testing Method Security
This commit is contained in:
José Carlos Valero Sánchez 2017-12-20 22:38:53 +00:00 committed by GitHub
commit b4dd01013f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 266 additions and 0 deletions

View File

@ -0,0 +1,11 @@
package org.baeldung.testmethodsecurity.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}

View File

@ -0,0 +1,30 @@
package org.baeldung.testmethodsecurity.entity;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
@SuppressWarnings("serial")
public class CustomUser extends User{
private String nickName;
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities,String nickName) {
super(username, password, authorities);
this.nickName = nickName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}

View File

@ -0,0 +1,41 @@
package org.baeldung.testmethodsecurity.repository;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.baeldung.testmethodsecurity.entity.CustomUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class UserRoleRepository {
static Map<String,CustomUser> DB_BASED_USER_MAPPING;
static{
DB_BASED_USER_MAPPING = new LinkedHashMap<>();
DB_BASED_USER_MAPPING.put("jane", new CustomUser("jane","1234", getGrantedAuthorities("ROLE_USER","ROLE_VIEWER"),"jane"));
DB_BASED_USER_MAPPING.put("john", new CustomUser("john","1234", getGrantedAuthorities("ROLE_EDITOR","ROLE_ADMIN"),"jane"));
DB_BASED_USER_MAPPING.put("jack", new CustomUser("jack","1234", getGrantedAuthorities("ROLE_USER","ROLE_REVIEWER"),"jane"));
}
private static List<GrantedAuthority> getGrantedAuthorities(String...roles){
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
for (String role : roles){
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
public CustomUser loadUserByUserName(String username){
if (DB_BASED_USER_MAPPING.containsKey(username)){
return DB_BASED_USER_MAPPING.get(username);
}
throw new UsernameNotFoundException("User "+username+" cannot be found");
}
}

View File

@ -0,0 +1,19 @@
package org.baeldung.testmethodsecurity.service;
import org.baeldung.testmethodsecurity.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
@Service("userDetailService")
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
UserRoleRepository userRoleRepo;
@Override
public UserDetails loadUserByUsername(String username) {
return userRoleRepo.loadUserByUserName(username);
}
}

View File

@ -0,0 +1,29 @@
package org.baeldung.testmethodsecurity.service;
import org.baeldung.testmethodsecurity.entity.CustomUser;
import org.baeldung.testmethodsecurity.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
@Service
public class UserRoleService {
@Autowired
UserRoleRepository userRoleRepository;
@PreAuthorize("hasRole('ROLE_VIEWER') or hasAuthority('SYS_ADMIN')")
public String getUsername(){
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser loadUserDetail(String username){
return userRoleRepository.loadUserByUserName(username);
}
}

View File

@ -0,0 +1,57 @@
package org.baeldung.testmethodsecurity;
import static org.junit.Assert.assertEquals;
import org.baeldung.testmethodsecurity.service.UserRoleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration
public class TestMethodSecurity{
@Autowired
UserRoleService userRoleService;
@Configuration
@ComponentScan("org.baeldung.testmethodsecurity.*")
public static class SpringConfig {
}
@Test
@WithMockUser(username="john",roles={"VIEWER"})
public void givenRoleViewer_whenCallGetUsername_thenReturnUsername(){
String userName = userRoleService.getUsername();
assertEquals("john", userName);
}
@Test
@WithMockUser(username="john",authorities={"SYS_ADMIN"})
public void givenAuthoritySysAdmin_whenCallGetUsername_thenReturnUsername(){
String userName = userRoleService.getUsername();
assertEquals("john", userName);
}
@Test(expected=AccessDeniedException.class)
@WithAnonymousUser
public void givenAnomynousUser_whenCallGetUsername_thenAccessDenied(){
userRoleService.getUsername();
}
@Test
@WithMockJohnViewer
public void givenMockedJohnViewer_whenCallGetUsername_thenReturnUsername(){
String userName = userRoleService.getUsername();
assertEquals("john", userName);
}
}

View File

@ -0,0 +1,34 @@
package org.baeldung.testmethodsecurity;
import static org.junit.Assert.assertEquals;
import org.baeldung.testmethodsecurity.service.UserRoleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration
@WithMockUser(username="john",roles={"VIEWER"})
public class TestWithMockUserAtClassLevel {
@Test
public void givenRoleViewer_whenCallGetUsername_thenReturnUsername(){
String currentUserName = userService.getUsername();
assertEquals("john",currentUserName);
}
@Autowired
UserRoleService userService;
@Configuration
@ComponentScan("org.baeldung.testmethodsecurity.*")
public static class SpringConfig {
}
}

View File

@ -0,0 +1,35 @@
package org.baeldung.testmethodsecurity;
import static org.junit.Assert.assertEquals;
import org.baeldung.testmethodsecurity.entity.CustomUser;
import org.baeldung.testmethodsecurity.service.UserRoleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration
public class TestWithUserDetails {
@Autowired
UserRoleService userService;
@Configuration
@ComponentScan("org.baeldung.testmethodsecurity.*")
public static class SpringConfig {
}
@Test
@WithUserDetails(value="john",userDetailsServiceBeanName="userDetailService")
public void whenJohn_callLoadUserDetail_thenOK(){
CustomUser user = userService.loadUserDetail("jane");
assertEquals("jane",user.getNickName());
}
}

View File

@ -0,0 +1,10 @@
package org.baeldung.testmethodsecurity;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.springframework.security.test.context.support.WithMockUser;
@Retention(RetentionPolicy.RUNTIME)
@WithMockUser(value="john",roles="VIEWER")
public @interface WithMockJohnViewer { }