编辑:我的解决方案
-
经过研究,ACL 更多的是在对象的安全列表上。
示例:您想保护员工表,某些员工记录(如 CEO、经理)只能由更高管理层访问。其余的员工记录可供所有人查看。这就是 ACL 要做的事情。
但是,当我们需要保护一些方法、控制器、url、静态内容...时,ACL 不适合这种情况。我们需要使用 hasAuthority 或 hasPermission 或 hasRole 或 ......
-
在一些网络系统中,只有很少的角色,管理员和用户。对于这种情况, hasAuthority 或 hasRole 就足够了。您只需为您想要保护的资源添加 @hasRole('admin') 注释。
但是,在某些系统中,存在动态角色,例如:admin 创建一个新角色“temporary_user”,但控制器或方法由@hasRole('user'),“temporary_user”无法访问。
在这种情况下,根据我的理解,有几种方法可以做。
根据您想要保护的资源数量创建多个角色。例如:将“role_getRecord”分配给getRecords(),将“role_writeRecord”分配给writeRecord()。这是一种无需更改 Spring 安全机制的方法,但会在您的数据库表上拥有很多角色,并且更复杂的系统会有更多角色。
-
@hasPermission - 这是我现在使用的。我创建了一个 CustomGrantedAuthority,以便更灵活地实现。我确实有一个 CustomUserDetailsService 和 CustomSpringSecurityUser,当用户登录时将创建 CustomSpringSecurityUser 并收集 CustomGrantedAuthority 然后返回 CustomSpringSecurityUser 到 CustomUserDetailsService。而且我确实有一个 CustomPermission 来验证权限。
请投票支持,如果您的想法有用,如果我错了或有更好的方法,请发表评论。
这是我的代码
CustomSpringSecurityUser
public class CustomSpringSecurityUser implements UserDetails, CredentialsContainer {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private String password;
private final String username;
private final Set<GrantedAuthority> authorities;
private final boolean accountNonExpired;
private final boolean accountNonLocked;
private final boolean credentialsNonExpired;
private final boolean enabled;
public CustomSpringSecurityUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
this(username, password, true, true, true, true, authorities);
}
public CustomSpringSecurityUser(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
if (((username == null) || "".equals(username)) || (password == null)) {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
this.username = username;
this.password = password;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
// this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
this.authorities = new HashSet<GrantedAuthority>(authorities);
}
public Collection<GrantedAuthority> getAuthorities() {
return authorities;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public boolean isEnabled() {
return enabled;
}
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public boolean isAccountNonLocked() {
return accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void eraseCredentials() {
password = null;
}
private static SortedSet<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities) {
Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
SortedSet<GrantedAuthority> sortedAuthorities =
new TreeSet<GrantedAuthority>(new AuthorityComparator());
for (GrantedAuthority grantedAuthority : authorities) {
Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");
sortedAuthorities.add(grantedAuthority);
}
return sortedAuthorities;
}
private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
public int compare(GrantedAuthority g1, GrantedAuthority g2) {
if (g2.getAuthority() == null) {
return -1;
}
if (g1.getAuthority() == null) {
return 1;
}
return g1.getAuthority().compareTo(g2.getAuthority());
}
}
@Override
public boolean equals(Object rhs) {
if (rhs instanceof CustomSpringSecurityUser) {
return username.equals(((CustomSpringSecurityUser) rhs).username);
}
return false;
}
@Override
public int hashCode() {
return username.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append(": ");
sb.append("Username: ").append(this.username).append("; ");
sb.append("Password: [PROTECTED]; ");
sb.append("Enabled: ").append(this.enabled).append("; ");
sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; ");
sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired).append("; ");
sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; ");
if (!authorities.isEmpty()) {
sb.append("Granted Authorities: ");
boolean first = true;
for (GrantedAuthority auth : authorities) {
if (!first) {
sb.append(",");
}
first = false;
sb.append(auth);
}
} else {
sb.append("Not granted any authorities");
}
return sb.toString();
}
}
CustomGrantedAuthority
public class CustomGrantedAuthority implements GrantedAuthority{
private String role;
private String permission,action;
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String getAuthority() {
return role;
}
}
CustomeUserDetailsService
@Service
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private OcUserService userService;
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
sg.com.xx.xx.table.OcUser u = userService.findByLoginname(username);
String pass = sg.com.xx.xx.table.OcUser.byteToHex(u.getPassword());
Collection<? extends GrantedAuthority> permissionList = userService.getPermissionByUserId(u.getId());
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
CustomSpringSecurityUser user = new CustomSpringSecurityUser(u.getLoginname(),
pass,
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
permissionList);
return user;
} catch (Exception e) {
logger.error("==============================================");
logger.error(e.toString());
return null;
}
}
}
自定义权限
public class CustomPermission implements PermissionEvaluator {
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
Collection<? extends GrantedAuthority> x = authentication.getAuthorities();
for(Object o : x)
{
CustomGrantedAuthority y = (CustomGrantedAuthority) o ;
if(y.getPermission().equals(targetDomainObject) )
if( y.getAction().equals(permission) )
return true;
}
return false;
}
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
int a = 5;
return true;
}
}