Back to Research
Authorization
RBAC
ABAC
Java
Spring Boot
Spring Security

RBAC vs ABAC in Java: when a role is not enough

The difference between RBAC and ABAC, how to tell you need attributes (branch, amount, time), and how to implement ABAC in Spring Boot without dropping RBAC.

8 min read

RBAC answers "what kind of action can this person take?". It struggles when the answer depends on which record, how much or when. That is ABAC territory.

The signal: role explosion

FINANCEIRO_SP_ATE_10K
FINANCEIRO_SP_ATE_50K
FINANCEIRO_RJ_ATE_10K
FINANCEIRO_RJ_ATE_50K
...

Branch and limit are attributes, not roles. Keep the role; add attributes.

RBAC + ABAC in Spring Boot

{
  "sub": "ana@acme.com",
  "permissions": ["pedidos:ler", "pedidos:aprovar"],
  "filial": "SP",
  "limite_aprovacao": "50000"
}
@Component("pedidoAuth")
public class PedidoAuthorization {

  private final PedidoRepository pedidos;

  public PedidoAuthorization(PedidoRepository pedidos) {
    this.pedidos = pedidos;
  }

  /** ABAC: atributos do usuário (filial, limite) contra atributos do pedido. */
  public boolean podeAprovar(Long pedidoId, Authentication auth) {
    if (!(auth instanceof JwtAuthenticationToken token)) {
      return false;
    }
    Pedido pedido = pedidos.findById(pedidoId).orElse(null);
    if (pedido == null) {
      return false;
    }
    String filial = token.getToken().getClaimAsString("filial");
    String limite = token.getToken().getClaimAsString("limite_aprovacao");
    if (filial == null || limite == null) {
      return false;
    }
    return pedido.getFilial().equals(filial)
        && pedido.getValor().compareTo(new BigDecimal(limite)) <= 0;
  }
}
@PostMapping("/api/pedidos/{id}/aprovar")
@PreAuthorize("hasAuthority('pedidos:aprovar') and @pedidoAuth.podeAprovar(#id, authentication)")
public Pedido aprovar(@PathVariable Long id) {
  return service.aprovar(id);
}

The permission check runs first and is cheap; only users with pedidos:aprovar reach the policy, which loads the order.

Context attributes

public boolean emHorarioComercial() {
  var agora = LocalTime.now(ZoneId.of("America/Sao_Paulo"));
  return !agora.isBefore(LocalTime.of(8, 0)) && agora.isBefore(LocalTime.of(18, 0));
}

Move state-dependent rules into the service

@Transactional
public Pedido aprovar(Long id, Authentication auth) {
  Pedido pedido = pedidos.findByIdForUpdate(id).orElseThrow();
  if (!politica.podeAprovar(pedido, auth)) {
    throw new AccessDeniedException("Fora da sua alçada");
  }
  return pedido.aprovar(auth.getName());
}

When ABAC is not enough either

"Can edit because it was shared with them" is a relationship: that is ReBAC (Google Zanzibar style).

Start from a solid base: RBAC in Java and Spring Boot.

Related articles