Permitting public endpoints
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shop must let guests browse the catalogue, and load balancers must reach the health check, while every change and every customer's data stays behind sign-in. How do you open exactly that much, and no more?
permitAll for the catalogue, health and API docs
permitAll() is a rule that lets every caller through for the matching requests, signed in or not, anonymousUser included.
Open exactly the public list from SECURITY.md in SecurityConfig: catalogue reads, /api, health and API docs. Everything else stays authenticated().
Example 1 · src/main/java/com/shoplite/common/security/SecurityConfig.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.common.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.SecurityFilterChain;
/** * Every security rule of ShopLite lives in this one class. * Rules are checked from top to bottom; the first rule that matches a request decides. */@Configuration@EnableWebSecuritypublic class SecurityConfig {
/** springdoc's JSON and Swagger UI pages (switched off in the prod profile). */ private static final String[] API_DOCS = { "/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html" };
@Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.GET, "/api/v1/products/**", "/api/v1/categories/**").permitAll() .requestMatchers(HttpMethod.GET, "/api").permitAll() .requestMatchers("/actuator/health/**").permitAll() .requestMatchers(API_DOCS).permitAll() // Spring Boot forwards errors to /error; it must stay open or real errors turn into 401 .requestMatchers("/error").permitAll() .anyRequest().authenticated()) .httpBasic(Customizer.withDefaults()) // The API reads credentials from the Authorization header, never from a cookie, // so a forged cross-site request cannot carry them: CSRF protection is not needed. .csrf(csrf -> csrf.disable()) .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); }}$ curl -i http://localhost:8080/api/v1/products/1
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Content-Length: 135
Date: Fri, 16 Oct 2026 06:38:57 GMT
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}
$ for u in /api /api/v1/categories /actuator/health/liveness /actuator/info /v3/api-docs /swagger-ui/index.html /api/v1/orders/14 /api/v1/customers; do printf "%-28s %s\n" $u $(curl -s -o /dev/null -w '%{http_code}' http://localhost:8080$u); done
/api 200
/api/v1/categories 200
/actuator/health/liveness 200
/actuator/info 401
/v3/api-docs 200
/swagger-ui/index.html 200
/api/v1/orders/14 401
/api/v1/customers 401What this code does
- The first four rules are the public list from
SECURITY.md;anyRequest().authenticated()covers everything else. - A guest now reads product 1, the categories,
/api, health and the API docs;/actuator/info, orders and customers stay at 401. @EnableWebSecurityis here for the integration test that runs without a web server (previous lesson).
ShopLite opens what SECURITY.md marks "guest: yes": reading products and categories, GET /api (name and version), the health check and the API docs. A guest who must sign in before seeing a price leaves the shop; load balancers and Kubernetes call /actuator/health/** without a password; Swagger UI and /v3/api-docs exist only in the dev profile, so opening their paths costs nothing in production.
Everything else keeps anyRequest().authenticated(): orders, customers, /actuator/info and every write. Open as little as possible, and write the reason next to each public rule.
management.endpoint.health.show-details=always shows database and disk details to anyone. That is acceptable on your laptop only; the prod profile keeps never.Matching by HTTP method and path
requestMatchers(method, patterns) matches requests by HTTP method and path pattern. * matches one path segment; ** at the end matches zero or more.
Open the catalogue for GET only, then send a POST to the same URL and see that it stays protected.
Example 2 · Same URL, different method
Runs in: the shoplite-api Spring Boot project
# Same URL, different methods: only GET is publiccurl "http://localhost:8080/api/v1/products?categoryId=2&sort=price,desc&size=2"curl -i -H "Content-Type: application/json" -d '{"name":"Toys","parentId":null}' http://localhost:8080/api/v1/categoriescurl -i -u "dev:$SHOPLITE_DEV_PASSWORD" -H "Content-Type: application/json" -d '{"name":"Toys","parentId":null}' http://localhost:8080/api/v1/categoriescurl -i http://localhost:8080/api/v1/products/99$ curl "http://localhost:8080/api/v1/products?categoryId=2&sort=price,desc&size=2"
{"content":[{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"page":0,"size":2,"totalElements":3,"totalPages":2}
$ curl -i -H "Content-Type: application/json" -d '{"name":"Toys","parentId":null}' http://localhost:8080/api/v1/categories
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
...
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:38:59 GMT
{"timestamp":"2026-10-16T06:38:59.132Z","status":401,"error":"Unauthorized","path":"/api/v1/categories"}
$ curl -i -u "dev:$SHOPLITE_DEV_PASSWORD" -H "Content-Type: application/json" -d '{"name":"Toys","parentId":null}' http://localhost:8080/api/v1/categories
HTTP/1.1 201
Location: http://localhost:8080/api/v1/categories/8
...
Content-Type: application/json
{"id":8,"name":"Toys","parentId":null}
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404
...
Content-Type: application/problem+json
{"detail":"Product 99 was not found.","instance":"/api/v1/products/99","status":404,"title":"Resource not found","type":"https://shoplite.example/problems/not-found"}What this code does
- Guests read paged products, but
POST /api/v1/categoriesis 401: the public rule namesHttpMethod.GETonly. - The dev user creates the category (201 with
Location). The 401 now has a JSON body because/erroris permitted (section 4). - A public endpoint keeps its normal errors: the missing product is still a 404 Problem Details response.
Without a method, requestMatchers("/api/v1/products/**") matches every method and would make POST, PATCH and DELETE public too: the most common and most dangerous permitAll mistake. The pattern /api/v1/products/** covers /api/v1/products, /api/v1/products/1 and /api/v1/products/1/anything, and one call can take several patterns.
A public endpoint keeps all its normal errors: GET /api/v1/products/99 is public and still answers 404 with ShopLite's Problem Details body. Security decides who may ask; the controller still decides the answer.
Find the bug
Find the unsafe public rule
Each rule is meant to open the catalogue for guests. Click the line that is wrong.
Guests may read products. What else do they get?
Round 1 of 3Rule order: specific rules first, anyRequest last
First match wins means Spring Security checks the rules from the top, and the first rule that matches a request decides; later rules are never looked at for that request.
Run the same three requests against two orders of the same rules, first in plain Java and then in the lab project.
Example 3 · First match wins, in plain Java
import java.util.List;
/** One access rule: an HTTP method (or "*" for any) and a path pattern ending in "/**" or exact. */record Rule(String method, String pattern, String access) {
boolean matches(String requestMethod, String path) { boolean methodOk = method.equals("*") || method.equals(requestMethod); boolean pathOk; if (pattern.equals("/**")) { pathOk = true; } else if (pattern.endsWith("/**")) { String base = pattern.substring(0, pattern.length() - 3); pathOk = path.equals(base) || path.startsWith(base + "/"); } else { pathOk = path.equals(pattern); } return methodOk && pathOk; }}
public class RuleOrderDemo {
/** Like Spring Security: rules are tried from the top, and the first match decides. */ static String decide(List<Rule> rules, String method, String path) { for (Rule rule : rules) { if (rule.matches(method, path)) { return rule.access() + " (rule: " + rule.method() + " " + rule.pattern() + ")"; } } return "deny (no rule matched)"; }
static void check(String title, List<Rule> rules) { System.out.println(title); String[][] requests = { { "GET", "/api/v1/products/1" }, { "POST", "/api/v1/products" }, { "GET", "/api/v1/orders/14" } }; for (String[] r : requests) { System.out.printf(" %-4s %-20s -> %s%n", r[0], r[1], decide(rules, r[0], r[1])); } }
public static void main(String[] args) { check("Specific rule first:", List.of( new Rule("GET", "/api/v1/products/**", "permitAll"), new Rule("*", "/api/v1/**", "authenticated"), new Rule("*", "/**", "authenticated"))); check("Broad rule first:", List.of( new Rule("*", "/api/v1/**", "authenticated"), new Rule("GET", "/api/v1/products/**", "permitAll"), new Rule("*", "/**", "authenticated"))); }}Specific rule first: GET /api/v1/products/1 -> permitAll (rule: GET /api/v1/products/**) POST /api/v1/products -> authenticated (rule: * /api/v1/**) GET /api/v1/orders/14 -> authenticated (rule: * /api/v1/**) Broad rule first: GET /api/v1/products/1 -> authenticated (rule: * /api/v1/**) POST /api/v1/products -> authenticated (rule: * /api/v1/**) GET /api/v1/orders/14 -> authenticated (rule: * /api/v1/**)
What this code does
decidetries the rules from the top and returns the first match, likeAuthorizationFilter.- With the specific GET rule first, product reads are public. With the broad
/api/v1/**rule first, the GET rule is never reached. - The last rule,
* /**, plays the part ofanyRequest(): it catches everything the others did not.
Example 4 · A broad rule hiding a specific one (security-lab)
Runs in: the security-lab practice project (Spring Boot 4.1)
// security-lab: a broad rule placed above the specific one.authorizeHttpRequests(auth -> auth .requestMatchers("/api/v1/**").authenticated() .requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll() // never reached .anyRequest().authenticated())$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/products
401
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/products/1
401
$ curl -s -o /dev/null -w "%{http_code}\n" -u asha:asha-pass-1 http://localhost:8080/api/v1/products/1
200
(no startup error: Spring cannot know which order you meant)What this code does
/api/v1/**matches every product URL, soauthenticated()decides and the permitAll line is dead.- The app starts normally; only a request (or a test) shows the mistake.
- Fix: move the
HttpMethod.GETproducts rule above the/api/v1/**rule.
So narrow rules (one method, one path) go first, broad ones (/api/v1/**) after them, and anyRequest() closes the list. When a broad rule sits above a specific one, the specific rule is dead: in the lab, requestMatchers("/api/v1/**").authenticated() above the GET products rule made the catalogue private again, with no error at startup. Spring only refuses rules after anyRequest(), because it cannot know which order you meant.
The opposite mistake is worse: a broad permitAll above a specific authenticated rule opens data by accident. Read the list top to bottom like if ... else if ..., and let tests guard it.
Predict the output
Which rule decides?
Walk the rules from the top. The first match wins.
Round 1 of 2
A guest sends GET /api/v1/products/1. What is the answer?
Why /error must be permitted
/error is the path Spring Boot forwards to when an error happens outside a controller. The forward passes the security filter chain again, as a new request.
Call a URL that the Spring Security firewall rejects, with and without the /error rule.
Example 5 · A firewall error with and without the /error rule
Runs in: the shoplite-api Spring Boot project
// Without this rule in SecurityConfig:.requestMatchers("/error").permitAll()
curl -i "http://localhost:8080/api/v1//products"Without the /error rule:
$ curl -i "http://localhost:8080/api/v1//products"
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
Content-Length: 0
Date: Fri, 16 Oct 2026 06:04:46 GMT
With the /error rule:
$ curl -i "http://localhost:8080/api/v1//products"
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:39:13 GMT
Connection: close
{"timestamp":"2026-10-16T06:39:13.965Z","status":400,"error":"Bad Request","path":"/api/v1//products"}What this code does
- Spring Security's firewall rejects the double slash and Boot forwards the 400 to
/error. - Without the rule, that forward needs sign-in, so the guest sees a misleading 401. With it, the real 400 comes through.
- The body is Boot's default error JSON, not ShopLite's Problem Details: the controller advice never ran, because the request never reached a controller.
If /error is not permitted, a guest who triggers such an error gets 401 instead of the real answer: the error page itself needs sign-in, and the real cause (400, 404, 405 and so on) is hidden. The firewall rejects odd URLs such as /api/v1//products (a double slash); with /error permitted the client sees the real 400.
This also changed the 401 itself. It is now forwarded to /error too, so it carries Boot's default JSON (timestamp, status, error, path) instead of an empty body. That is not yet ShopLite's Problem Details format; the Roles and permissions module replaces it with the unauthorized (401) and forbidden (403) problem types from SECURITY.md.
Testing public and protected endpoints
@WithMockUser runs a test request as a signed-in user, with no real password. httpBasic(...) sends real Basic credentials instead.
Test the access table with @WebMvcTest, @Import(SecurityConfig.class), @WithMockUser and httpBasic(...): no server and no database.
Example 6 · src/test/java/com/shoplite/common/security/SecurityRulesTest.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.common.security;
import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.ArgumentMatchers.any;import static org.mockito.BDDMockito.given;import static org.mockito.Mockito.verifyNoInteractions;import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.context.annotation.Import;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.security.test.context.support.WithMockUser;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.assertj.MockMvcTester;
import com.shoplite.category.CategoryService;import com.shoplite.customer.CustomerService;import com.shoplite.order.OrderService;import com.shoplite.product.ProductResponse;import com.shoplite.product.ProductService;
/** Who may call what: the rules in SecurityConfig, checked without a database or a server. */@WebMvcTest@Import(SecurityConfig.class)@ActiveProfiles("test")class SecurityRulesTest {
private static final String NEW_PRODUCT = """ {"sku": "ACC-KB100", "name": "Zebronics Wireless Keyboard", "categoryId": 4, "price": 999.00, "stock": 30} """;
@Autowired private MockMvcTester mvc;
@MockitoBean private ProductService productService;
@MockitoBean private CategoryService categoryService;
@MockitoBean private CustomerService customerService;
@MockitoBean private OrderService orderService;
@Test void guestCanBrowseTheCatalogue() { given(productService.get(1L)).willReturn(new ProductResponse(1L, "MOB-RN13", "Redmi Note 13 5G", 2L, "Mobiles", new BigDecimal("17999.00"), 40, true));
assertThat(mvc.get().uri("/api/v1/products/1")).hasStatusOk(); assertThat(mvc.get().uri("/api/v1/categories")).hasStatusOk(); }
@Test void guestCannotChangeTheCatalogue() { assertThat(mvc.post().uri("/api/v1/products").contentType(MediaType.APPLICATION_JSON).content(NEW_PRODUCT)) .hasStatus(HttpStatus.UNAUTHORIZED) .hasHeader("WWW-Authenticate", "Basic realm=\"Realm\", charset=\"UTF-8\""); assertThat(mvc.delete().uri("/api/v1/categories/7")).hasStatus(HttpStatus.UNAUTHORIZED); verifyNoInteractions(productService, categoryService); // the controller was never reached }
@Test void guestCannotReadCustomersOrOrders() { assertThat(mvc.get().uri("/api/v1/customers/1")).hasStatus(HttpStatus.UNAUTHORIZED); assertThat(mvc.get().uri("/api/v1/orders/14")).hasStatus(HttpStatus.UNAUTHORIZED); }
@Test @WithMockUser(username = "dev", roles = "ADMIN") void signedInUserCanCreateAProduct() { given(productService.create(any())).willReturn(new ProductResponse(16L, "ACC-KB100", "Zebronics Wireless Keyboard", 4L, "Accessories", new BigDecimal("999.00"), 30, true));
assertThat(mvc.post().uri("/api/v1/products").contentType(MediaType.APPLICATION_JSON).content(NEW_PRODUCT)) .hasStatus(HttpStatus.CREATED); }
@Test void wrongPasswordIs401AndRightPasswordWorks() { assertThat(mvc.get().uri("/api/v1/customers/1").with(httpBasic("test", "wrong-password"))) .hasStatus(HttpStatus.UNAUTHORIZED); assertThat(mvc.get().uri("/api/v1/customers/1").with(httpBasic("test", "test-only-password"))) .hasStatusOk(); }}$ ./mvnw test ... [INFO] Running com.shoplite.common.security.SecurityRulesTest [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 21.60 s -- in com.shoplite.common.security.SecurityRulesTest [INFO] Running com.shoplite.order.OrderControllerTest [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.901 s -- in com.shoplite.order.OrderControllerTest [INFO] Running com.shoplite.product.ProductControllerTest [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.207 s -- in com.shoplite.product.ProductControllerTest [INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS After deleting "/api/v1/products/**" from the first permitAll rule: [ERROR] com.shoplite.common.security.SecurityRulesTest.guestCanBrowseTheCatalogue -- Time elapsed: 0.120 s <<< FAILURE! [HTTP status code] expected: 200 but was: 401
What this code does
@WebMvcTestwith no controller list loads all controllers, so every service they need is a@MockitoBean;@Import(SecurityConfig.class)brings the real rules.- Guests get 200 for reads and 401 for writes;
verifyNoInteractionsproves the rejected requests never reached a controller. - Removing the products rule makes
guestCanBrowseTheCataloguefail with "expected: 200 but was: 401": the test guards the access table.
@WebMvcTest starts only the web layer with MockMvc; @Import(SecurityConfig.class) adds your real rules; spring-security-test adds the two helpers. Write at least one test per rule: a guest may read the catalogue (200), a guest cannot write (401 with WWW-Authenticate, and the service mock was never called), a guest cannot read customers or orders (401), and a signed-in user can write. The test profile defines its own user (test / test-only-password in application-test.properties), so tests never need your dev password.
The existing slice tests need the same three annotations, or they hit Boot's defaults and fail with 401 and 403, as in the first lesson of this module. For a quick check by hand, curl -s -o /dev/null -w "%{http_code}" prints just the status code.
Next step
Check your understanding
12 quick questions