Protección de endpoints con reglas de acceso personalizadas
Vaya más allá de las comprobaciones de roles simples escribiendo lógica de autorización personalizada en Spring Security 6 mediante AuthorizationManager, expresiones SpEL y request matchers.
Protección de endpoints con reglas de acceso personalizadas es una lección gratuita de Spring Security 6 & JWT Authentication en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Security 6 & JWT Authentication, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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.
Preguntas frecuentes
¿La lección «Protección de endpoints con reglas de acceso personalizadas» es gratis?
Sí — el texto completo de «Protección de endpoints con reglas de acceso personalizadas» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Security 6 & JWT Authentication, actualiza a CoddyKit PRO. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.
¿Qué aprenderé en «Protección de endpoints con reglas de acceso personalizadas»?
Vaya más allá de las comprobaciones de roles simples escribiendo lógica de autorización personalizada en Spring Security 6 mediante AuthorizationManager, expresiones SpEL y request matchers. Practicas Spring Security 6 & JWT Authentication con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Spring Security 6 & JWT Authentication?
No se requiere experiencia previa. Spring Security 6 & JWT Authentication en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Protección de endpoints con reglas de acceso personalizadas»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Spring Security 6 & JWT Authentication?
Sí. Cada lección de Spring Security 6 & JWT Authentication incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Control de acceso basado en roles (RBAC)
- Seguridad a nivel de método con anotaciones
- Análisis detallado de la configuración de HttpSecurity
- Protección de endpoints con reglas de acceso personalizadas