Reputation: 2056
I am working in a Java application with Java 8, using the stream functionality I have this POJO:
public class Authority implements GrantedAuthority {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String authority;
public Authority(String authority) {
this.authority = authority;
}
@Override
public String getAuthority() {
return authority;
}
@Override
public String toString() {
return "Authority [authority=" + authority + "]";
}
}
and
public class User implements Serializable, UserDetails {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<>();
userRoles.forEach(ur -> authorities.add(new Authority(ur.getRole().getName())));
return authorities;
}
public boolean isAdmin() {
return getAuthorities().stream().filter
(o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
}
}
and I've created this Junit to check if everything os OK
@Test
public void isAdminTests() {
User adminUser = UserUtils.createBasicUser("[email protected]", "[email protected]", true);
Set<UserRole> adminUserRoles = new HashSet<>();
adminUserRoles.add(new UserRole(adminUser, new Role(RolesEnum.ADMIN)));
adminUser.getUserRoles().addAll(adminUserRoles);
System.out.print(adminUser.getAuthorities());
assertTrue (adminUser.isAdmin());
}
and this is the value in the console:
[Authority [authority=ROLE_ADMIN]]
But I have an assertion error
Upvotes: 1
Views: 491
Reputation: 239
Not sure, but try this:
here
public boolean isAdmin () {
return getAuthorities().stream().filter
(o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
}
change to smth like this:
o.getAuthority().equals(new GrantedAuthority(RolesEnum.Admin.name()))).findFirst().isPresent();
Because when you creating spring authorities "ROLE_" is added by default as a prefix to your String role representation
Upvotes: 1
Reputation: 4044
My guess is that you compare the Authority Object (which is a String IIRC) with the enum object
o.getAuthority().equals(RolesEnum.ADMIN))
You have to compare these two diffrent objects so that a match is possible
You could try
o.getAuthority().equals(RolesEnum.ADMIN.name()))
when you can ensure that the enum names always are the same as the role names.
Upvotes: 4