Endpunkte mit benutzerdefinierten Zugriffsregeln absichern
Gehen Sie über einfache Rollenprüfungen hinaus, indem Sie in Spring Security 6 mit AuthorizationManager, SpEL-Ausdrücken und Request Matchern eine eigene Autorisierungslogik schreiben.
Endpunkte mit benutzerdefinierten Zugriffsregeln absichern ist eine kostenlose Spring Security 6 & JWT Authentication-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Spring Security 6 & JWT Authentication-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Spring Security 6 & JWT Authentication-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Endpunkte mit benutzerdefinierten Zugriffsregeln absichern“ kostenlos?
Ja — der vollständige Text von „Endpunkte mit benutzerdefinierten Zugriffsregeln absichern“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Spring Security 6 & JWT Authentication-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Spring Security 6 & JWT Authentication-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Endpunkte mit benutzerdefinierten Zugriffsregeln absichern“?
Gehen Sie über einfache Rollenprüfungen hinaus, indem Sie in Spring Security 6 mit AuthorizationManager, SpEL-Ausdrücken und Request Matchern eine eigene Autorisierungslogik schreiben. Du übst Spring Security 6 & JWT Authentication mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Spring Security 6 & JWT Authentication zu starten?
Keine Vorkenntnisse erforderlich. Spring Security 6 & JWT Authentication auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Endpunkte mit benutzerdefinierten Zugriffsregeln absichern“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Spring Security 6 & JWT Authentication-Lektion Code schreiben und ausführen?
Ja. Jede Spring Security 6 & JWT Authentication-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Rollenbasierte Zugriffskontrolle (RBAC)
- Sicherheit auf Methodenebene mit Annotationen
- HttpSecurity-Konfiguration im Detail
- Endpunkte mit benutzerdefinierten Zugriffsregeln absichern