Authorization
RBAC
Multi-tenant
Spring Boot
Java
SaaS
Multi-tenant RBAC in Spring Boot: per-customer roles without leaking data
How each SaaS customer builds its own roles, how to carry tenant and permissions in the token, and how to stop a permitted user from reading another customer's data.
8 min read
In a SaaS, RBAC has two layers: does the user have pedidos:ler, and whose orders are they reading? An Acme user with full permissions must not see a single Beta record.
1. The model
CREATE TABLE permissoes ( -- global: definida pelo código chave VARCHAR(100) PRIMARY KEY ); CREATE TABLE papeis ( -- por cliente: definida pelo cliente id UUID PRIMARY KEY, tenant_id VARCHAR(64) NOT NULL, nome VARCHAR(100) NOT NULL, UNIQUE (tenant_id, nome) ); CREATE TABLE papel_permissoes ( papel_id UUID REFERENCES papeis(id), permissao_chave VARCHAR(100) REFERENCES permissoes(chave), PRIMARY KEY (papel_id, permissao_chave) ); CREATE TABLE membros ( -- a mesma pessoa pode estar em vários clientes usuario_id UUID NOT NULL, tenant_id VARCHAR(64) NOT NULL, papel_id UUID REFERENCES papeis(id), PRIMARY KEY (usuario_id, tenant_id, papel_id) );
Permissions are global (defined by code); roles belong to each customer.
2. One token per customer
{
"sub": "8f14e45f-...",
"tenant_id": "acme",
"permissions": ["pedidos:ler", "pedidos:aprovar"]
}@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
var authorities = new JwtGrantedAuthoritiesConverter();
authorities.setAuthoritiesClaimName("permissions");
authorities.setAuthorityPrefix("");
var converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(authorities);
return converter;
}3. Both checks on the endpoint
@Component("tenant")
public class TenantGuard {
/** O tenant do caminho é o mesmo do token? */
public boolean is(String tenantId, Authentication auth) {
return auth instanceof JwtAuthenticationToken token
&& tenantId != null
&& tenantId.equals(token.getToken().getClaimAsString("tenant_id"));
}
public static String atual(Authentication auth) {
if (auth instanceof JwtAuthenticationToken token) {
String id = token.getToken().getClaimAsString("tenant_id");
if (id != null) {
return id;
}
}
throw new AccessDeniedException("Token sem tenant");
}
}@RestController
@RequestMapping("/api/tenants/{tenantId}/pedidos")
public class PedidoController {
@GetMapping("/{id}")
@PreAuthorize("@tenant.is(#tenantId, authentication) and hasAuthority('pedidos:ler')")
public Pedido buscar(@PathVariable String tenantId, @PathVariable Long id) {
return pedidos.findByTenantIdAndId(tenantId, id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}
}4. Filter in the repository
public interface PedidoRepository extends JpaRepository<Pedido, Long> {
Optional<Pedido> findByTenantIdAndId(String tenantId, Long id);
List<Pedido> findByTenantId(String tenantId);
}public List<Pedido> listar(Authentication auth) {
return pedidos.findByTenantId(TenantGuard.atual(auth));
}Avoid findById on customer data: that is how IDOR happens. PostgreSQL Row-Level Security or a Hibernate filter adds another layer.
Common mistakes
- Checking the permission but not the tenant, or the opposite.
- Trusting a tenant header without comparing it with the token.
- Cache keys without the tenant.