Authorization: URL rules and method security
Harry
· 14 Sep 2026
· 1 views
Advertisement
URL-based authorization
The most common rules protect whole sections of the app by path and role:
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/api/**").hasAnyRole("USER", "ADMIN")
.requestMatchers(HttpMethod.POST, "/orders").authenticated()
.anyRequest().permitAll());
hasRole("ADMIN")– requiresROLE_ADMIN.hasAnyRole(...)– any of several roles.authenticated()– any logged-in user;permitAll()– everyone.
Method-level security
For finer control, secure individual service methods. Enable it once:
@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig { }
Then annotate methods with a rule that is checked before the method runs:
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) { ... }
@PreAuthorize("#username == authentication.name")
public Profile getProfile(String username) { ... }
The second example uses a SpEL expression so a user can only fetch their own profile – authorization based on the data, not just the role.
Reading the current user
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
boolean isAdmin = auth.getAuthorities().stream()
.anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
Key points
- Protect URL patterns with
hasRole,hasAnyRole,authenticatedandpermitAll. - Enable
@EnableMethodSecurityand use@PreAuthorizefor per-method rules. - SpEL expressions allow data-aware checks like “only your own profile”.
- The authenticated user is available from the
SecurityContext.