Skip to content

Commit b0d331f

Browse files
committed
[BAEL-1411:tlinh2110] Add example for PostAuthorize
1 parent 2bac6f8 commit b0d331f

2 files changed

Lines changed: 20 additions & 5 deletions

File tree

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,13 @@ public boolean isValidUsername3(String username) {
6464
@PreAuthorize("#username == authentication.principal.username")
6565
public String getMyRoles(String username) {
6666
SecurityContext securityContext = SecurityContextHolder.getContext();
67-
return securityContext
68-
.getAuthentication()
69-
.getAuthorities()
70-
.stream()
71-
.map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
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(","));
7274
}
7375

7476
@PostAuthorize("returnObject.username == authentication.principal.nickName")

‎spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,19 @@ public void givenUserJohn_whenCallGetMyRolesWithJohn_thenReturnRoles() {
9797
public void givenUserJane_whenCallGetMyRolesWithJane_thenAccessDenied() {
9898
userRoleService.getMyRoles("jane");
9999
}
100+
101+
@Test
102+
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
103+
public void givenUserJohn_whenCallGetMyRoles2WithJohn_thenReturnRoles() {
104+
String roles = userRoleService.getMyRoles2("john");
105+
assertEquals("ROLE_ADMIN,ROLE_USER,ROLE_VIEWER", roles);
106+
}
107+
108+
@Test(expected = AccessDeniedException.class)
109+
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
110+
public void givenUserJane_whenCallGetMyRoles2WithJane_thenAccessDenied() {
111+
userRoleService.getMyRoles2("jane");
112+
}
100113

101114
@Test(expected = AccessDeniedException.class)
102115
@WithAnonymousUser

0 commit comments

Comments
 (0)