Skip to content

Commit 0d84b1f

Browse files
committed
[tlinh2110@gmail.com] Restructure to Method Security
1 parent 665195d commit 0d84b1f

12 files changed

Lines changed: 323 additions & 101 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
{
15+
}

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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package org.baeldung.testmethodsecurity.entity;
1+
package org.baeldung.methodsecurity.entity;
22

33
import java.util.Collection;
44

spring-security-core/src/main/java/org/baeldung/testmethodsecurity/repository/UserRoleRepository.java renamed to spring-security-core/src/main/java/org/baeldung/methodsecurity/repository/UserRoleRepository.java

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

33
import java.util.ArrayList;
44
import java.util.LinkedHashMap;
55
import java.util.List;
66
import java.util.Map;
77

8-
import org.baeldung.testmethodsecurity.entity.CustomUser;
8+
import org.baeldung.methodsecurity.entity.CustomUser;
99
import org.springframework.security.core.GrantedAuthority;
1010
import org.springframework.security.core.authority.SimpleGrantedAuthority;
1111
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@@ -38,4 +38,20 @@ public CustomUser loadUserByUserName(String username){
3838
throw new UsernameNotFoundException("User "+username+" cannot be found");
3939
}
4040

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+
4157
}

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: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
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 getUsernameInLowerCase(){
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
68+
.getAuthentication()
69+
.getAuthorities()
70+
.stream().map(auth -> auth.getAuthority())
71+
.collect(Collectors.joining(","));
72+
}
73+
74+
@PostAuthorize("returnObject.username == authentication.principal.nickName")
75+
public CustomUser loadUserDetail(String username){
76+
return userRoleRepository.loadUserByUserName(username);
77+
}
78+
79+
@PreFilter("filterObject != authentication.principal.username")
80+
public String joinUsernames(List<String> usernames){
81+
return usernames.stream().collect(Collectors.joining(";"));
82+
}
83+
84+
@PreFilter(value="filterObject != authentication.principal.username",filterTarget="usernames")
85+
public String joinUsernamesAndRoles(List<String> usernames,List<String> roles){
86+
return usernames.stream().collect(Collectors.joining(";"))
87+
+":"+roles.stream().collect(Collectors.joining(";"));
88+
}
89+
90+
@PostFilter("filterObject != authentication.principal.username")
91+
public List<String> getAllUsernamesExceptCurrent(){
92+
return userRoleRepository.getAllUsernames();
93+
}
94+
95+
@IsViewer
96+
public String getUsername4(){
97+
SecurityContext securityContext = SecurityContextHolder.getContext();
98+
return securityContext.getAuthentication().getName();
99+
}
100+
101+
@PreAuthorize("#username == authentication.principal.username")
102+
@PostAuthorize("returnObject.username == authentication.principal.nickName")
103+
public CustomUser securedLoadUserDetail(String username){
104+
return userRoleRepository.loadUserByUserName(username);
105+
}
106+
107+
}

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

Lines changed: 0 additions & 29 deletions
This file was deleted.
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
package org.baeldung.methodsecurity;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertTrue;
5+
6+
import java.util.ArrayList;
7+
import java.util.List;
8+
9+
import org.baeldung.methodsecurity.service.UserRoleService;
10+
import org.junit.Test;
11+
import org.junit.runner.RunWith;
12+
import org.springframework.beans.factory.annotation.Autowired;
13+
import org.springframework.context.annotation.ComponentScan;
14+
import org.springframework.context.annotation.Configuration;
15+
import org.springframework.security.access.AccessDeniedException;
16+
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
17+
import org.springframework.security.test.context.support.WithAnonymousUser;
18+
import org.springframework.security.test.context.support.WithMockUser;
19+
import org.springframework.test.context.ContextConfiguration;
20+
import org.springframework.test.context.junit4.SpringRunner;
21+
22+
@RunWith(SpringRunner.class)
23+
@ContextConfiguration
24+
public class TestMethodSecurity{
25+
26+
@Autowired
27+
UserRoleService userRoleService;
28+
29+
@Configuration
30+
@ComponentScan("org.baeldung.methodsecurity.*")
31+
public static class SpringConfig {
32+
33+
}
34+
35+
@Test(expected=AuthenticationCredentialsNotFoundException.class)
36+
public void givenNoSecurity_whenCallGetUsername_thenReturnException(){
37+
String userName = userRoleService.getUsername();
38+
assertEquals("john", userName);
39+
}
40+
41+
@Test
42+
@WithMockUser(username="john",roles={"VIEWER"})
43+
public void givenRoleViewer_whenCallGetUsername_thenReturnUsername(){
44+
String userName = userRoleService.getUsername();
45+
assertEquals("john", userName);
46+
}
47+
48+
@Test
49+
@WithMockUser(username="john",roles={"EDITOR"})
50+
public void givenUsernameJohn_whenCallIsValidUsername_thenReturnTrue(){
51+
boolean isValid = userRoleService.isValidUsername("john");
52+
assertEquals(true, isValid);
53+
}
54+
55+
@Test(expected = AccessDeniedException.class)
56+
@WithMockUser(username = "john", roles = { "ADMIN" })
57+
public void givenRoleAdmin_whenCallGetUsername_thenReturnAccessDenied() {
58+
userRoleService.getUsername();
59+
}
60+
61+
@Test(expected = AccessDeniedException.class)
62+
@WithMockUser(username = "john", roles = {"USER"})
63+
public void givenRoleUser_whenCallGetUsername2_thenReturnAccessDenied() {
64+
userRoleService.getUsername2();
65+
}
66+
67+
@Test
68+
@WithMockUser(username="john",roles={"VIEWER","EDITOR"})
69+
public void givenRoleViewer_whenCallGetUsername2_thenReturnUsername(){
70+
String userName = userRoleService.getUsername2();
71+
assertEquals("john", userName);
72+
}
73+
74+
@Test
75+
@WithMockUser(username="john",roles={"VIEWER"})
76+
public void givenUsernameJerry_whenCallIsValidUsername2_thenReturnFalse(){
77+
boolean isValid = userRoleService.isValidUsername2("jerry");
78+
assertEquals(false, isValid);
79+
}
80+
81+
@Test
82+
@WithMockUser(username="JOHN",authorities={"SYS_ADMIN"})
83+
public void givenAuthoritySysAdmin_whenCallGetUsernameInLowerCase_thenReturnUsername(){
84+
String username = userRoleService.getUsernameInLowerCase();
85+
assertEquals("john", username);
86+
}
87+
88+
@Test
89+
@WithMockUser(username="john",roles={"ADMIN","USER","VIEWER"})
90+
public void givenUserJohn_whenCallGetMyRolesWithJohn_thenReturnRoles(){
91+
String roles = userRoleService.getMyRoles("john");
92+
assertEquals("ROLE_ADMIN,ROLE_USER,ROLE_VIEWER", roles);
93+
}
94+
95+
@Test(expected=AccessDeniedException.class)
96+
@WithMockUser(username="john",roles={"ADMIN","USER","VIEWER"})
97+
public void givenUserJane_whenCallGetMyRolesWithJane_thenAccessDenied(){
98+
userRoleService.getMyRoles("jane");
99+
}
100+
101+
@Test(expected=AccessDeniedException.class)
102+
@WithAnonymousUser
103+
public void givenAnomynousUser_whenCallGetUsername_thenAccessDenied(){
104+
userRoleService.getUsername();
105+
}
106+
107+
@Test
108+
@WithMockJohnViewer
109+
public void givenMockedJohnViewer_whenCallGetUsername_thenReturnUsername(){
110+
String userName = userRoleService.getUsername();
111+
assertEquals("john", userName);
112+
}
113+
114+
@Test
115+
@WithMockUser(username="jane")
116+
public void givenListContainCurrentUsername_whenJoinUsernames_thenReturnUsernames(){
117+
List<String> usernames = new ArrayList<>();
118+
usernames.add("jane");
119+
usernames.add("john");
120+
usernames.add("jack");
121+
String containCurrentUser = userRoleService.joinUsernames(usernames);
122+
assertEquals("john;jack", containCurrentUser);
123+
124+
}
125+
126+
@Test
127+
@WithMockUser(username="john")
128+
public void givenListNotContainCurrentUsername_whenCallContainCurrentUser_thenReturnAccessDenied(){
129+
List<String> usernames = new ArrayList<>();
130+
usernames.add("jane");
131+
usernames.add("john");
132+
usernames.add("jack");
133+
134+
List<String> roles = new ArrayList<>();
135+
roles.add("ROLE_ADMIN");
136+
roles.add("ROLE_TEST");
137+
138+
String containCurrentUser = userRoleService.joinUsernamesAndRoles(usernames,roles);
139+
assertEquals("jane;jack:ROLE_ADMIN;ROLE_TEST", containCurrentUser);
140+
}
141+
142+
@Test
143+
@WithMockUser(username="john")
144+
public void givenUserJohn_whenCallGetAllUsernamesExceptCurrent_thenReturnOtherusernames(){
145+
List<String> others = userRoleService.getAllUsernamesExceptCurrent();
146+
assertEquals(2, others.size());
147+
assertTrue(others.contains("jane"));
148+
assertTrue(others.contains("jack"));
149+
}
150+
151+
@Test
152+
@WithMockUser(username="john",roles={"VIEWER"})
153+
public void givenRoleViewer_whenCallGetUsername4_thenReturnUsername(){
154+
String userName = userRoleService.getUsername4();
155+
assertEquals("john", userName);
156+
}
157+
158+
@Test(expected=AccessDeniedException.class)
159+
@WithMockUser(username="john")
160+
public void givenDefaultRole_whenCallGetUsername4_thenAccessDenied(){
161+
userRoleService.getUsername4();
162+
}
163+
}

0 commit comments

Comments
 (0)