Lock Down Endpoints

In this lesson, we're going to lock down certain endpoints to only certain roles.

Configuring Role-Based Access

Spring Security allows us to restrict access to API endpoints based on user roles.

In our application, we want to ensure that only users with the organizer role can access the events controller endpoints.

Here's how we implement this in the SecurityConfig class:

.authorizeHttpRequests(authorize -> authorize .requestMatchers(HttpMethod.GET, "/api/v1/published-events/**").permitAll() .requestMatchers("/api/v1/events").hasRole("ORGANIZER") // Catch all rule .anyRequest().authenticated())

The .hasRole("ORGANIZER") method is used to restrict access to users with the organizer role.

When using hasRole(), Spring Security automatically adds the ROLE_ prefix to the role name, so we don't need to include it in our configuration.

Testing Role-Based Access

To verify our role-based access is working correctly, we can test with different user roles:

  1. When logged in as an organizer user (with the ROLE_ORGANIZER role), requests to the events endpoint return HTTP 200 OK.

  2. When logged in as an attendee user (without the ROLE_ORGANIZER role), requests to the events endpoint return HTTP 403 Forbidden.

Summary

  • Locked down the events endpoints to only organizer users
© 2026 Devtiro Ltd. All rights reserved