Protegendo endpoints com regras de acesso personalizadas
Vá além das verificações simples de funções escrevendo uma lógica de autorização personalizada no Spring Security 6 usando AuthorizationManager, expressões SpEL e correspondedores de solicitações.
Protegendo endpoints com regras de acesso personalizadas é uma aula grátis de Spring Security 6 & JWT Authentication no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Security 6 & JWT Authentication, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Security 6 & JWT Authentication inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Custom Access Rules?
Roles and methods cover most cases, but real apps need finer control: only the owner of a resource may edit it, or access depends on the time of day or a feature flag.
Spring Security 6 lets you express these rules declaratively or programmatically.
The authorizeHttpRequests DSL
In Spring Security 6 the modern way to secure URLs is authorizeHttpRequests. Each matcher maps a request pattern to an access rule.
http.authorizeHttpRequests(auth -> auth
.requestMatchers('/public/**').permitAll()
.requestMatchers('/admin/**').hasRole('ADMIN')
.anyRequest().authenticated());Matching by HTTP Method
You can scope rules to a specific HTTP method, so reads and writes have different requirements.
http.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, '/api/orders/**').authenticated()
.requestMatchers(HttpMethod.POST, '/api/orders/**').hasRole('MANAGER'));SpEL with access()
The access() rule takes a Spring Expression Language (SpEL) condition for dynamic logic that plain matchers cannot express.
http.authorizeHttpRequests(auth -> auth
.requestMatchers('/reports/**')
.access(new WebExpressionAuthorizationManager(
"hasRole('ANALYST') and request.getHeader('X-Region') == 'EU'")));The AuthorizationManager Interface
For full control, implement AuthorizationManager. It returns an AuthorizationDecision that grants or denies access based on the authentication and the request.
public interface AuthorizationManager<T> {
AuthorizationDecision check(Supplier<Authentication> auth, T object);
}Writing a Custom AuthorizationManager
Here is a manager that only allows access during business hours. The supplier gives the current user; the object holds request context.
AuthorizationManager<RequestAuthorizationContext> businessHours =
(auth, ctx) -> {
int hour = LocalTime.now().getHour();
boolean ok = hour >= 9 && hour < 18;
return new AuthorizationDecision(ok);
};Plugging It In
Attach your custom manager to a matcher with access(). Any request to the path is now evaluated by your logic.
http.authorizeHttpRequests(auth -> auth
.requestMatchers('/maintenance/**').access(businessHours)
.anyRequest().authenticated());Owner-Based Access
A common rule: only the resource owner can modify it. You can read a path variable from the request context to compare against the logged-in user.
AuthorizationManager<RequestAuthorizationContext> ownerOnly =
(auth, ctx) -> {
String pathUser = ctx.getVariables().get('userId');
boolean same = auth.get().getName().equals(pathUser);
return new AuthorizationDecision(same);
};Combining Rules
Spring evaluates matchers top to bottom and stops at the first match. Order matters: put specific rules before broad ones, and always end with a catch-all like anyRequest().
Denying by Default
A secure baseline denies everything not explicitly allowed. Use denyAll() as the final rule when you want a strict allow-list.
http.authorizeHttpRequests(auth -> auth
.requestMatchers('/health').permitAll()
.anyRequest().denyAll());Testing Access Rules
Verify your rules with @WithMockUser and MockMvc. Assert that authorized users get 200 and unauthorized users get 403.
mockMvc.perform(get('/admin/dashboard'))
.andExpect(status().isForbidden());Quick Check
Test your understanding of custom access rules.
Recap
You learned to write custom authorization in Spring Security 6:
- Use the
authorizeHttpRequestsDSL with path and method matchers - Apply SpEL conditions via
access() - Implement
AuthorizationManagerfor dynamic, owner-based, or time-based rules - Order matters; end with a catch-all and prefer deny-by-default
These tools let you enforce business-specific security policies precisely.
Perguntas Frequentes
A aula “Protegendo endpoints com regras de acesso personalizadas” é grátis?
Sim — o texto completo de “Protegendo endpoints com regras de acesso personalizadas” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Security 6 & JWT Authentication, atualize para CoddyKit PRO. O curso de Spring Security 6 & JWT Authentication inclui 4 aulas no total.
O que vou aprender em “Protegendo endpoints com regras de acesso personalizadas”?
Vá além das verificações simples de funções escrevendo uma lógica de autorização personalizada no Spring Security 6 usando AuthorizationManager, expressões SpEL e correspondedores de solicitações. Você pratica Spring Security 6 & JWT Authentication com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Spring Security 6 & JWT Authentication?
Nenhuma experiência prévia é necessária. Spring Security 6 & JWT Authentication no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Protegendo endpoints com regras de acesso personalizadas”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Spring Security 6 & JWT Authentication?
Sim. Cada aula de Spring Security 6 & JWT Authentication inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Controle de acesso baseado em funções (RBAC)
- Segurança no nível de métodos com anotações
- Aprofundamento na configuração do HttpSecurity
- Protegendo endpoints com regras de acesso personalizadas