Skip to content

Commit fc8e9ae

Browse files
Merge pull request eugenp#3336 from linhvovn/BAEL-1411
[Bael 1411-tlinh2110] Add resources for Method Security
2 parents 07aad44 + 70638b9 commit fc8e9ae

16 files changed

Lines changed: 497 additions & 181 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package org.baeldung.methodsecurity.annotation;
2+
3+
import java.lang.annotation.ElementType;
4+
import java.lang.annotation.Retention;
5+
import java.lang.annotation.RetentionPolicy;
6+
import java.lang.annotation.Target;
7+
8+
import org.springframework.security.access.prepost.PreAuthorize;
9+
10+
@Target(ElementType.METHOD)
11+
@Retention(RetentionPolicy.RUNTIME)
12+
@PreAuthorize("hasRole('VIEWER')")
13+
public @interface IsViewer {
14+
}

spring-security-core/src/main/java/org/baeldung/testmethodsecurity/config/MethodSecurityConfig.java renamed to spring-security-core/src/main/java/org/baeldung/methodsecurity/config/MethodSecurityConfig.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
package org.baeldung.testmethodsecurity.config;
1+
package org.baeldung.methodsecurity.config;
22

33
import org.springframework.context.annotation.Configuration;
44
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
55
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
66

77
@Configuration
8-
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
8+
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
99
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
1010

1111
}

spring-security-core/src/main/java/org/baeldung/testmethodsecurity/entity/CustomUser.java renamed to spring-security-core/src/main/java/org/baeldung/methodsecurity/entity/CustomUser.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
package org.baeldung.testmethodsecurity.entity;
1+
package org.baeldung.methodsecurity.entity;
22

33
import java.util.Collection;
44

55
import org.springframework.security.core.GrantedAuthority;
66
import org.springframework.security.core.userdetails.User;
77

88
@SuppressWarnings("serial")
9-
public class CustomUser extends User{
10-
9+
public class CustomUser extends User {
10+
1111
private String nickName;
1212

1313
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
1414
super(username, password, authorities);
1515
}
16-
17-
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities,String nickName) {
16+
17+
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities, String nickName) {
1818
super(username, password, authorities);
1919
this.nickName = nickName;
2020
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package org.baeldung.methodsecurity.repository;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedHashMap;
5+
import java.util.List;
6+
import java.util.Map;
7+
8+
import org.baeldung.methodsecurity.entity.CustomUser;
9+
import org.springframework.security.core.GrantedAuthority;
10+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
11+
import org.springframework.security.core.userdetails.UsernameNotFoundException;
12+
import org.springframework.stereotype.Service;
13+
14+
@Service
15+
public class UserRoleRepository {
16+
17+
static Map<String, CustomUser> DB_BASED_USER_MAPPING;
18+
19+
static {
20+
DB_BASED_USER_MAPPING = new LinkedHashMap<>();
21+
DB_BASED_USER_MAPPING.put("jane", new CustomUser("jane", "1234", getGrantedAuthorities("ROLE_USER", "ROLE_VIEWER"), "jane"));
22+
DB_BASED_USER_MAPPING.put("john", new CustomUser("john", "1234", getGrantedAuthorities("ROLE_EDITOR", "ROLE_ADMIN"), "jane"));
23+
DB_BASED_USER_MAPPING.put("jack", new CustomUser("jack", "1234", getGrantedAuthorities("ROLE_USER", "ROLE_REVIEWER"), "jane"));
24+
}
25+
26+
private static List<GrantedAuthority> getGrantedAuthorities(String... roles) {
27+
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
28+
for (String role : roles) {
29+
authorities.add(new SimpleGrantedAuthority(role));
30+
}
31+
return authorities;
32+
}
33+
34+
public CustomUser loadUserByUserName(String username) {
35+
if (DB_BASED_USER_MAPPING.containsKey(username)) {
36+
return DB_BASED_USER_MAPPING.get(username);
37+
}
38+
throw new UsernameNotFoundException("User " + username + " cannot be found");
39+
}
40+
41+
public boolean isValidUsername(String username) {
42+
return DB_BASED_USER_MAPPING.containsKey(username);
43+
}
44+
45+
public boolean isValidRole(String roleName) {
46+
return roleName.startsWith("ROLE_");
47+
}
48+
49+
public List<String> getAllUsernames() {
50+
List<String> usernames = new ArrayList<>();
51+
usernames.add("jane");
52+
usernames.add("john");
53+
usernames.add("jack");
54+
return usernames;
55+
}
56+
57+
}

spring-security-core/src/main/java/org/baeldung/testmethodsecurity/service/CustomUserDetailsService.java renamed to spring-security-core/src/main/java/org/baeldung/methodsecurity/service/CustomUserDetailsService.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
package org.baeldung.testmethodsecurity.service;
1+
package org.baeldung.methodsecurity.service;
22

3-
import org.baeldung.testmethodsecurity.repository.UserRoleRepository;
3+
import org.baeldung.methodsecurity.repository.UserRoleRepository;
44
import org.springframework.beans.factory.annotation.Autowired;
55
import org.springframework.security.core.userdetails.UserDetails;
66
import org.springframework.security.core.userdetails.UserDetailsService;
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package org.baeldung.methodsecurity.service;
2+
3+
import org.springframework.security.access.prepost.PreAuthorize;
4+
import org.springframework.stereotype.Service;
5+
6+
@Service
7+
@PreAuthorize("hasRole('ROLE_ADMIN')")
8+
public class SystemService {
9+
10+
public String getSystemYear(){
11+
return "2017";
12+
}
13+
14+
public String getSystemDate(){
15+
return "31-12-2017";
16+
}
17+
18+
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
package org.baeldung.methodsecurity.service;
2+
3+
import java.util.List;
4+
import java.util.stream.Collectors;
5+
6+
import javax.annotation.security.RolesAllowed;
7+
8+
import org.baeldung.methodsecurity.annotation.IsViewer;
9+
import org.baeldung.methodsecurity.entity.CustomUser;
10+
import org.baeldung.methodsecurity.repository.UserRoleRepository;
11+
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.security.access.annotation.Secured;
13+
import org.springframework.security.access.prepost.PostAuthorize;
14+
import org.springframework.security.access.prepost.PostFilter;
15+
import org.springframework.security.access.prepost.PreAuthorize;
16+
import org.springframework.security.access.prepost.PreFilter;
17+
import org.springframework.security.core.context.SecurityContext;
18+
import org.springframework.security.core.context.SecurityContextHolder;
19+
import org.springframework.stereotype.Service;
20+
21+
@Service
22+
public class UserRoleService {
23+
24+
@Autowired
25+
UserRoleRepository userRoleRepository;
26+
27+
@Secured("ROLE_VIEWER")
28+
public String getUsername() {
29+
SecurityContext securityContext = SecurityContextHolder.getContext();
30+
return securityContext.getAuthentication().getName();
31+
}
32+
33+
@Secured({ "ROLE_VIEWER", "ROLE_EDITOR" })
34+
public boolean isValidUsername(String username) {
35+
return userRoleRepository.isValidUsername(username);
36+
}
37+
38+
@RolesAllowed("ROLE_VIEWER")
39+
public String getUsername2() {
40+
SecurityContext securityContext = SecurityContextHolder.getContext();
41+
return securityContext.getAuthentication().getName();
42+
}
43+
44+
@RolesAllowed({ "ROLE_VIEWER", "ROLE_EDITOR" })
45+
public boolean isValidUsername2(String username) {
46+
return userRoleRepository.isValidUsername(username);
47+
}
48+
49+
@PreAuthorize("hasRole('ROLE_VIEWER')")
50+
public String getUsernameInUpperCase() {
51+
return getUsername().toUpperCase();
52+
}
53+
54+
@PreAuthorize("hasAuthority('SYS_ADMIN')")
55+
public String getUsernameLC() {
56+
return getUsername().toLowerCase();
57+
}
58+
59+
@PreAuthorize("hasRole('ROLE_VIEWER') or hasRole('ROLE_EDITOR')")
60+
public boolean isValidUsername3(String username) {
61+
return userRoleRepository.isValidUsername(username);
62+
}
63+
64+
@PreAuthorize("#username == authentication.principal.username")
65+
public String getMyRoles(String username) {
66+
SecurityContext securityContext = SecurityContextHolder.getContext();
67+
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
68+
}
69+
70+
@PostAuthorize("#username == authentication.principal.username")
71+
public String getMyRoles2(String username) {
72+
SecurityContext securityContext = SecurityContextHolder.getContext();
73+
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
74+
}
75+
76+
@PostAuthorize("returnObject.username == authentication.principal.nickName")
77+
public CustomUser loadUserDetail(String username) {
78+
return userRoleRepository.loadUserByUserName(username);
79+
}
80+
81+
@PreFilter("filterObject != authentication.principal.username")
82+
public String joinUsernames(List<String> usernames) {
83+
return usernames.stream().collect(Collectors.joining(";"));
84+
}
85+
86+
@PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames")
87+
public String joinUsernamesAndRoles(List<String> usernames, List<String> roles) {
88+
return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";"));
89+
}
90+
91+
@PostFilter("filterObject != authentication.principal.username")
92+
public List<String> getAllUsernamesExceptCurrent() {
93+
return userRoleRepository.getAllUsernames();
94+
}
95+
96+
@IsViewer
97+
public String getUsername4() {
98+
SecurityContext securityContext = SecurityContextHolder.getContext();
99+
return securityContext.getAuthentication().getName();
100+
}
101+
102+
@PreAuthorize("#username == authentication.principal.username")
103+
@PostAuthorize("returnObject.username == authentication.principal.nickName")
104+
public CustomUser securedLoadUserDetail(String username) {
105+
return userRoleRepository.loadUserByUserName(username);
106+
}
107+
108+
}

‎spring-security-core/src/main/java/org/baeldung/testmethodsecurity/repository/UserRoleRepository.java‎

Lines changed: 0 additions & 41 deletions
This file was deleted.

‎spring-security-core/src/main/java/org/baeldung/testmethodsecurity/service/UserRoleService.java‎

Lines changed: 0 additions & 29 deletions
This file was deleted.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package org.baeldung.methodsecurity;
2+
3+
import static org.junit.Assert.*;
4+
5+
import org.baeldung.methodsecurity.service.SystemService;
6+
import org.junit.Test;
7+
import org.junit.runner.RunWith;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.context.annotation.ComponentScan;
10+
import org.springframework.context.annotation.Configuration;
11+
import org.springframework.security.access.AccessDeniedException;
12+
import org.springframework.security.test.context.support.WithMockUser;
13+
import org.springframework.test.context.ContextConfiguration;
14+
import org.springframework.test.context.junit4.SpringRunner;
15+
16+
@RunWith(SpringRunner.class)
17+
@ContextConfiguration
18+
public class TestClassLevelSecurity {
19+
20+
@Autowired
21+
SystemService systemService;
22+
23+
@Configuration
24+
@ComponentScan("org.baeldung.methodsecurity.*")
25+
public static class SpringConfig {
26+
27+
}
28+
29+
@Test
30+
@WithMockUser(username="john",roles={"ADMIN"})
31+
public void givenRoleAdmin_whenCallGetSystemYear_return2017(){
32+
String systemYear = systemService.getSystemYear();
33+
assertEquals("2017",systemYear);
34+
}
35+
36+
@Test(expected=AccessDeniedException.class)
37+
@WithMockUser(username="john",roles={"VIEWER"})
38+
public void givenRoleViewer_whenCallGetSystemYear_returnAccessDenied(){
39+
String systemYear = systemService.getSystemYear();
40+
assertEquals("2017",systemYear);
41+
}
42+
43+
@Test
44+
@WithMockUser(username="john",roles={"ADMIN"})
45+
public void givenRoleAdmin_whenCallGetSystemDate_returnDate(){
46+
String systemYear = systemService.getSystemDate();
47+
assertEquals("31-12-2017",systemYear);
48+
}
49+
}

0 commit comments

Comments
 (0)