我正在使用Java 8在Java应用程序中工作,使用流功能 我有这个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 + "]";
}
}
和
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();
}
}
我已经创建了这个Junit以检查是否一切正常
@Test
public void isAdminTests() {
User adminUser = UserUtils.createBasicUser("user2@gmail.com", "user2@gmail.com", 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());
}
这是控制台中的值:
[Authority [authority=ROLE_ADMIN]]
但我有一个断言错误
答案 0 :(得分:4)
我的猜测是你将Authority对象(它是一个String IIRC)与枚举对象
进行比较o.getAuthority().equals(RolesEnum.ADMIN))
您必须比较这两个不同的对象才能匹配
你可以尝试
o.getAuthority().equals(RolesEnum.ADMIN.name()))
当您可以确保枚举名称始终与角色名称相同时。
答案 1 :(得分:1)
不确定,但试试这个:
这里
public boolean isAdmin () {
return getAuthorities().stream().filter
(o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
}
像这样改为smth:
o.getAuthority().equals(new GrantedAuthority(RolesEnum.Admin.name()))).findFirst().isPresent();
因为当你创建弹簧权威时,#R; _ ROLE _&#34;默认情况下添加为String角色表示的前缀