Skip to content

Commit 4cfc16f

Browse files
committed
Fix adding more implied roles in the RoleHierarchy Builder.
Closes gh-15717 Signed-off-by: Niels Basjes <[email protected]>
1 parent 3117fef commit 4cfc16f

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

core/src/main/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImpl.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -295,11 +295,11 @@ public RoleHierarchyImpl build() {
295295
}
296296

297297
private Builder addHierarchy(String role, String... impliedRoles) {
298-
Set<GrantedAuthority> withPrefix = new HashSet<>();
298+
Set<GrantedAuthority> withPrefix = this.hierarchy.computeIfAbsent(this.rolePrefix.concat(role),
299+
(r) -> new HashSet<>());
299300
for (String impliedRole : impliedRoles) {
300301
withPrefix.add(new SimpleGrantedAuthority(this.rolePrefix.concat(impliedRole)));
301302
}
302-
this.hierarchy.put(this.rolePrefix.concat(role), withPrefix);
303303
return this;
304304
}
305305

core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImplTests.java

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2016 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -259,6 +259,24 @@ public void testBuilderWithDefaultRolePrefix() {
259259
.containsExactlyInAnyOrderElementsOf(allAuthorities);
260260
}
261261

262+
@Test
263+
public void testBuilderWithRepeatedRoleBuilder() {
264+
RoleHierarchyImpl roleHierarchyImpl = RoleHierarchyImpl.withDefaultRolePrefix()
265+
.role("A")
266+
.implies("B")
267+
.role("A") // Adding more implied roles to the existing role 'A'
268+
.implies("C", "D")
269+
.build();
270+
271+
List<GrantedAuthority> flatAuthorities = AuthorityUtils.createAuthorityList("ROLE_A");
272+
List<GrantedAuthority> allAuthorities = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B", "ROLE_C",
273+
"ROLE_D");
274+
275+
assertThat(roleHierarchyImpl).isNotNull();
276+
assertThat(roleHierarchyImpl.getReachableGrantedAuthorities(flatAuthorities))
277+
.containsExactlyInAnyOrderElementsOf(allAuthorities);
278+
}
279+
262280
@Test
263281
public void testBuilderWithRolePrefix() {
264282
RoleHierarchyImpl roleHierarchyImpl = RoleHierarchyImpl.withRolePrefix("CUSTOM_PREFIX_")

0 commit comments

Comments
 (0)