我正在尝试使用 Spring Security 来实现角色和权限(权限)。我正在使用 JWT 来管理会话。这是我为我的角色创建的枚举类
@RequiredArgsConstructor
public enum Role {
USER(Collections.emptySet()),
ADMIN(Set.of(ADMIN_READ,
ADMIN_CREATE,
ADMIN_DELETE,
ADMIN_UPDATE,
MANAGER_CREATE,
MANAGER_DELETE,
MANAGER_UPDATE,
MANAGER_READ)),
MANAGER(Set.of(
MANAGER_CREATE,
MANAGER_DELETE,
MANAGER_UPDATE,
MANAGER_READ));
@Getter
private final Set<Permissions> permissions;
public List<SimpleGrantedAuthority> getAuthorities(){
//converting the permissions of the roles into a list of authorities
var authorities = getPermissions()
.stream()
.map(permissions ->new SimpleGrantedAuthority(permissions.name()))
.collect(Collectors.toList());
//adding the role also as part of the authorities so this will contain the role and the permissions inside the authority list
authorities.add(new SimpleGrantedAuthority("ROLE_" + this.name()));
return authorities;
}
}
这是我的权限类
@Getter
@RequiredArgsConstructor
public enum Permissions {
ADMIN_READ("admin::read"),
ADMIN_UPDATE("admin::update"),
ADMIN_CREATE("admin::create"),
ADMIN_DELETE("admin::delete"),
MANAGER_READ("management::read"),
MANAGER_UPDATE("management::update"),
MANAGER_CREATE("management::create"),
MANAGER_DELETE("management::delete");
private final String permissions;
}
这是安全配置类的片段
.requestMatchers(ADMIN_URL).hasRole(ADMIN.name())
.requestMatchers(HttpMethod.GET,ADMIN_URL).hasAuthority("ROLE_"+ADMIN_READ.name())
.requestMatchers(HttpMethod.POST,ADMIN_URL).hasAuthority(ADMIN_CREATE.name())
.requestMatchers(HttpMethod.PUT,ADMIN_URL).hasAuthority(ADMIN_UPDATE.name())
.requestMatchers(HttpMethod.DELETE,ADMIN_URL).hasAuthority(ADMIN_DELETE.name())
我创建了具有管理员权限的用户,但是当我调用我的端点(ADMIN_URL)时,我收到 403 响应(使用邮递员进行测试)
我已经尝试向当局添加roles_,但我仍然收到相同的错误
我刚刚发现,当要调用
getAuthorities()
来检查用户的角色时,会调用 hasRole("ADMIN")
方法。因此,我的getAuthortites()
需要返回用户可用的权限列表。
我将 Users 类中的
getAuthorties()
方法更改为此并且有效。
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return role.getAuthorities();
}