将 GrantedAuthority 视为“许可”或“权利”。这些“权限”(通常)表示为字符串(使用getAuthority()方法)。这些字符串可让您识别权限并让您的选民决定是否授予对某些内容的访问权限。
您可以通过将用户放入安全上下文中来向用户授予不同的 GrantedAuthority(权限)。您通常通过实现自己的 UserDetailsService 来实现,该服务返回返回所需的 GrantedAuthorities 的 UserDetails 实现。
角色(如在许多示例中使用的那样)只是具有命名约定的“权限”,即角色是以前缀开头的 GrantedAuthority ROLE_。没有什么了。角色只是一个 GrantedAuthority - 一个“权限” - 一个“权利”。您会在 Spring Security 中看到很多地方,其中带有ROLE_前缀的角色被特别处理,例如在 RoleVoter 中,ROLE_前缀被用作默认值。这允许您提供不带ROLE_前缀的角色名称。在 Spring security 4 之前,这种对“角色”的特殊处理并没有得到非常一致的遵循,并且权限和角色通常被视为相同(例如,hasAuthority()hasRole())。使用 Spring Security 4,角色的处理更加一致,处理“角色”的代码(如RoleVoter、hasRole表达式等)总是ROLE_为您添加前缀。所以意味着与自动添加前缀hasAuthority('ROLE_ADMIN')相同。有关更多信息,请参阅 spring security 3 到 4迁移指南。hasRole('ADMIN')ROLE_
但仍然:角色只是具有特殊ROLE_前缀的权限。所以在 Spring security 3@PreAuthorize("hasRole('ROLE_XYZ')")中与 Spring security 4 相同@PreAuthorize("hasAuthority('ROLE_XYZ')"),在 Spring security 4@PreAuthorize("hasRole('XYZ')")中与@PreAuthorize("hasAuthority('ROLE_XYZ')").
关于您的用例:
用户具有角色并且角色可以执行某些操作。
您最终可能会GrantedAuthorities选择用户所属的角色以及角色可以执行的操作。GrantedAuthorities角色有前缀,ROLE_操作有前缀OP_。操作权限的示例可以是OP_DELETE_ACCOUNT,OP_CREATE_USER等OP_RUN_BATCH_JOB。角色可以是ROLE_ADMIN,ROLE_USER等ROLE_OWNER。
您最终可能会让您的实体GrantedAuthority在这个(伪代码)示例中实现:
@Entity
class Role implements GrantedAuthority {
@Id
private String id;
@ManyToMany
private final List<Operation> allowedOperations = new ArrayList<>();
@Override
public String getAuthority() {
return id;
}
public Collection<GrantedAuthority> getAllowedOperations() {
return allowedOperations;
}
}
@Entity
class User {
@Id
private String id;
@ManyToMany
private final List<Role> roles = new ArrayList<>();
public Collection<Role> getRoles() {
return roles;
}
}
@Entity
class Operation implements GrantedAuthority {
@Id
private String id;
@Override
public String getAuthority() {
return id;
}
}
您在数据库中创建的角色和操作的 id 将是 GrantedAuthority 表示,例如ROLE_ADMIN等OP_DELETE_ACCOUNT。当用户通过身份验证时,请确保从 UserDetails.getAuthorities() 返回其所有角色的所有 GrantedAuthorities 和相应的操作方法。
示例:具有 id 的管理员角色具有ROLE_ADMIN操作OP_DELETE_ACCOUNT, OP_READ_ACCOUNT,OP_RUN_BATCH_JOB分配给它。具有 id 的用户角色具有ROLE_USER操作OP_READ_ACCOUNT。
如果管理员登录生成的安全上下文将具有 GrantedAuthorities:
ROLE_ADMIN, OP_DELETE_ACCOUNT, OP_READ_ACCOUNT,OP_RUN_BATCH_JOB
如果用户登录它,它将具有:
ROLE_USER,OP_READ_ACCOUNT
UserDetailsService 将负责收集所有角色和这些角色的所有操作,并通过返回的 UserDetails 实例中的 getAuthorities() 方法使它们可用。