[BAEL-1411:tlinh2110] Add example for PostAuthorize
This commit is contained in:
parent
2bac6f88e7
commit
b0d331f2dd
|
@ -64,11 +64,13 @@ public class UserRoleService {
|
||||||
@PreAuthorize("#username == authentication.principal.username")
|
@PreAuthorize("#username == authentication.principal.username")
|
||||||
public String getMyRoles(String username) {
|
public String getMyRoles(String username) {
|
||||||
SecurityContext securityContext = SecurityContextHolder.getContext();
|
SecurityContext securityContext = SecurityContextHolder.getContext();
|
||||||
return securityContext
|
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
|
||||||
.getAuthentication()
|
}
|
||||||
.getAuthorities()
|
|
||||||
.stream()
|
@PostAuthorize("#username == authentication.principal.username")
|
||||||
.map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
|
public String getMyRoles2(String username) {
|
||||||
|
SecurityContext securityContext = SecurityContextHolder.getContext();
|
||||||
|
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostAuthorize("returnObject.username == authentication.principal.nickName")
|
@PostAuthorize("returnObject.username == authentication.principal.nickName")
|
||||||
|
|
|
@ -97,6 +97,19 @@ public class TestMethodSecurity {
|
||||||
public void givenUserJane_whenCallGetMyRolesWithJane_thenAccessDenied() {
|
public void givenUserJane_whenCallGetMyRolesWithJane_thenAccessDenied() {
|
||||||
userRoleService.getMyRoles("jane");
|
userRoleService.getMyRoles("jane");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
|
||||||
|
public void givenUserJohn_whenCallGetMyRoles2WithJohn_thenReturnRoles() {
|
||||||
|
String roles = userRoleService.getMyRoles2("john");
|
||||||
|
assertEquals("ROLE_ADMIN,ROLE_USER,ROLE_VIEWER", roles);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = AccessDeniedException.class)
|
||||||
|
@WithMockUser(username = "john", roles = { "ADMIN", "USER", "VIEWER" })
|
||||||
|
public void givenUserJane_whenCallGetMyRoles2WithJane_thenAccessDenied() {
|
||||||
|
userRoleService.getMyRoles2("jane");
|
||||||
|
}
|
||||||
|
|
||||||
@Test(expected = AccessDeniedException.class)
|
@Test(expected = AccessDeniedException.class)
|
||||||
@WithAnonymousUser
|
@WithAnonymousUser
|
||||||
|
|
Loading…
Reference in New Issue