Authorization
RBAC
Java
Spring Boot
JPA
Spring Security
Roles and permissions in the database with Spring Boot, JPA, and Spring Security
How to model users, roles, and permissions with JPA, load them in a UserDetailsService without N+1, and protect endpoints by permission in Spring Boot.
9 min read
When roles and permissions live in your application's own database, Spring Security needs a bridge: something has to read the user, roles and permissions and turn them into GrantedAuthority. This guide builds that bridge with JPA, from the tables to a protected endpoint.
Premise: code checks permissions, and roles only group permissions. See the RBAC in Java and Spring Boot guide for why.
1. Entities
@Entity
@Table(name = "permissoes")
public class Permissao {
@Id
private String chave; // "pedidos:aprovar"
private String descricao;
}
@Entity
@Table(name = "papeis")
public class Papel {
@Id @GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String nome; // "FINANCEIRO"
@ManyToMany
@JoinTable(name = "papel_permissoes",
joinColumns = @JoinColumn(name = "papel_id"),
inverseJoinColumns = @JoinColumn(name = "permissao_chave"))
private Set<Permissao> permissoes = new HashSet<>();
}
@Entity
@Table(name = "usuarios")
public class Usuario {
@Id @GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String email;
private String senhaHash;
private boolean ativo = true;
@ManyToMany
@JoinTable(name = "usuario_papeis",
joinColumns = @JoinColumn(name = "usuario_id"),
inverseJoinColumns = @JoinColumn(name = "papel_id"))
private Set<Papel> papeis = new HashSet<>();
}Use Set, not List: fetching two lists in one join fetch throws MultipleBagFetchException.
2. One query, no N+1
public interface UsuarioRepository extends JpaRepository<Usuario, Long> {
// Uma consulta só: usuário, papéis e permissões.
@Query("""
select distinct u from Usuario u
left join fetch u.papeis p
left join fetch p.permissoes
where u.email = :email
""")
Optional<Usuario> findComPermissoes(@Param("email") String email);
}3. The UserDetailsService
@Service
public class UsuarioDetailsService implements UserDetailsService {
private final UsuarioRepository usuarios;
public UsuarioDetailsService(UsuarioRepository usuarios) {
this.usuarios = usuarios;
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) {
Usuario usuario = usuarios.findComPermissoes(email)
.orElseThrow(() -> new UsernameNotFoundException("Usuário não encontrado"));
Set<GrantedAuthority> authorities = new HashSet<>();
for (Papel papel : usuario.getPapeis()) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + papel.getNome()));
for (Permissao permissao : papel.getPermissoes()) {
authorities.add(new SimpleGrantedAuthority(permissao.getChave()));
}
}
return User.withUsername(usuario.getEmail())
.password(usuario.getSenhaHash())
.authorities(authorities)
.disabled(!usuario.isAtivo())
.build();
}
}Each role becomes ROLE_X (for hasRole) and each permission an authority without prefix (for hasAuthority).
4. Security configuration
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health").permitAll()
.requestMatchers(HttpMethod.GET, "/api/pedidos/**").hasAuthority("pedidos:ler")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}5. Protecting the endpoint
@RestController
@RequestMapping("/api/pedidos")
public class PedidoController {
@PostMapping("/{id}/aprovar")
@PreAuthorize("hasAuthority('pedidos:aprovar')")
public Pedido aprovar(@PathVariable Long id) {
return service.aprovar(id);
}
}Seed data
INSERT INTO permissoes (chave, descricao) VALUES
('pedidos:ler', 'Ver pedidos'),
('pedidos:aprovar', 'Aprovar pedidos');
INSERT INTO papeis (id, nome) VALUES (1, 'ATENDIMENTO'), (2, 'FINANCEIRO');
INSERT INTO papel_permissoes (papel_id, permissao_chave) VALUES
(1, 'pedidos:ler'),
(2, 'pedidos:ler'), (2, 'pedidos:aprovar');Production caveats
- Authorities live in the session: a removed permission keeps working until the next login.
- Stateless APIs run the UserDetailsService on every request: cache it or carry permissions in a JWT.
- Multi-tenant apps add a
tenant_idto roles; see multi-tenant RBAC in Spring Boot. - Test the rules: testing permissions in Spring Security.