Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 38 ยท Projects and Practice

Project: A Secured Inventory Service

Build a JWT-secured inventory microservice in Micronaut with roles, stock rules, optimistic locking, health and metrics, plus a runnable end-to-end Java stand-in.

The second project is a small inventory service that other services call to ask "how many of item X do we have?" and to reserve stock. It is security-sensitive (only trusted callers may change stock), concurrency-sensitive (two orders must not take the last item) and operations-sensitive (it must report its health). That makes it a good test of everything you learned in this chapter.

The Micronaut code below is read-only because the framework is not available on this site. The runnable stand-in implements the same security checks, stock rules and conflict detection in plain Java.

Requirements

  • Anyone authenticated can read stock (GET /inventory/{sku}).
  • Role ROLE_WAREHOUSE can adjust stock (POST /inventory/{sku}/adjust).
  • Role ROLE_ORDERS (another service) can reserve stock (POST /inventory/{sku}/reserve).
  • Stock can never go negative.
  • Concurrent updates are detected, not silently overwritten.
  • /health is open for the load balancer; everything else needs a valid token.

Who may do what

Any user Read stock.
WAREHOUSE Adjust stock.
1 / 2

Configuration

YAML
micronaut:
  application:
    name: inventory
  security:
    authentication: bearer
    token:
      jwt:
        signatures:
          jwks:
            auth:
              url: "${JWKS_URL}"           # tokens are issued by a separate auth service
    intercept-url-map:
      - pattern: /health
        access: [isAnonymous()]
endpoints:
  health:
    enabled: true
    sensitive: false

This service is a resource server: it never sees passwords, only tokens from the identity provider, as explained in OAuth 2.0 and OpenID Connect and JWT Tokens. The JWKS URL comes from the environment, as in Configuration Files and Environments.

The controller

Java
@Validated
@Controller("/inventory")
@Secured(SecurityRule.IS_AUTHENTICATED)
class InventoryController {

    private final InventoryService service;
    InventoryController(InventoryService service) { this.service = service; }

    @Get("/{sku}")
    StockView stock(String sku) { return service.get(sku); }

    @Post("/{sku}/adjust")
    @Secured("ROLE_WAREHOUSE")
    StockView adjust(String sku, @Body @Valid AdjustRequest body) {
        return service.adjust(sku, body.delta(), body.expectedVersion());
    }

    @Post("/{sku}/reserve")
    @Secured("ROLE_ORDERS")
    StockView reserve(String sku, @Body @Valid ReserveRequest body) {
        return service.reserve(sku, body.quantity());
    }
}

@Serdeable
record AdjustRequest(int delta, long expectedVersion) {}

@Serdeable
record ReserveRequest(@Positive int quantity) {}

Business rules and optimistic locking

Two warehouse staff may edit the same item at the same time. Optimistic locking solves this without holding database locks: each row has a version; an update says "change this row only if its version is still N". If somebody else changed it, the update touches zero rows and you report a conflict (HTTP 409).

Java
@MappedEntity("stock")
public record StockEntity(@Id String sku, int quantity, @Version long version) {}

@JdbcRepository(dialect = Dialect.POSTGRES)
public interface StockRepository extends CrudRepository<StockEntity, String> {}

Micronaut Data's @Version annotation makes update fail with OptimisticLockException if the version changed; map that to 409 with an @Error handler. Wrap the multi-step logic in @Transactional.

Java
@Singleton
class InventoryService {
    @Transactional
    StockView reserve(String sku, int quantity) {
        StockEntity s = repository.findById(sku).orElseThrow(() -> new NotFoundException(sku));
        if (s.quantity() < quantity) throw new OutOfStockException(sku, s.quantity());
        return view(repository.update(new StockEntity(sku, s.quantity() - quantity, s.version())));
    }
}

Try it: security, rules and versions together

This stand-in includes a signed-token check (HMAC), role rules, a non-negative stock rule and optimistic locking, so you can try each failure path. Tokens are created by a helper to keep the output predictable.

Java Secured inventory (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Health and metrics

Register a counter for each outcome so you can alert on spikes:

Java
registry.counter("inventory.reservations", "result", "ok").increment();
registry.counter("inventory.reservations", "result", "out_of_stock").increment();

Expose /prometheus, protect it on a management port, and add a health indicator that checks the database. See Metrics, Health and Tracing.

Tests to write

  1. Anonymous request to /inventory/SKU-1 returns 401.
  2. A token with ROLE_ORDERS calling adjust returns 403.
  3. Reserving more than available returns 409 and leaves the stock unchanged.
  4. Two concurrent adjusts with the same expected version: one 200, one 409.
  5. /health is reachable without a token.

Generate test tokens with a signing key configured in application-test.yml, and read Testing with Micronaut Test for the client setup.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is optimistic locking?

    A version column detects that another writer changed the row first, without holding locks.
  2. 2. Where should the caller's role come from?

    Only data the server has verified, such as a signed token, may decide permissions.
  3. 3. Which status fits a reservation that exceeds available stock?

    The request conflicts with the current state of the resource.
  4. 4. Why is this service a resource server?

    It verifies bearer tokens via the provider's keys and never handles credentials.

Summary

  • Combine bearer-token security, role rules and validation to protect an API.
  • Enforce domain rules in the service and detect concurrent writes with a version column.
  • Open only what must be open (/health), keep management endpoints private.
  • Write tests for every deny path as well as the happy path.

Next: Project: Event-Driven Orders