What is microservice authorization, and where do the decision points sit?
Authentication answers "who is calling?" Authorization answers "may this caller do this, right now?" The two are often bundled together, but they fail in different ways. A valid token tells you the identity is real. It does not tell you whether that identity should be able to refund an order in another tenant's account.
Every authorization decision can be stated as four inputs:
- Subject: the user or workload making the request, plus attributes such as roles, tenant and group membership.
- Action: what the subject wants to do, for example
read,approveordelete. - Resource: the target, for example
invoice/8812, along with its owner, tenant and state. - Context: request-time facts such as time, source network, device posture, or whether MFA was used.
RBAC covers only part of this model. It maps subjects to actions through roles. Many real rules need resource attributes and context as well.
In a typical microservice request path, checks can happen at four points:
- API gateway: coarse checks at the edge, such as "is this route open to this client?" It sees the token and the URL, but not resource state.
- Service mesh sidecar: service-to-service rules, such as "may
billingcallledger?" It sees workload identity, not business objects. - Service handler: the first point that can load the resource and evaluate ownership or state.
- Data layer: row-level filtering, so queries only return records the subject is allowed to see.
The further a check sits from the data, the less it knows. The rest of this article uses these terms: a policy decision point (PDP) evaluates the rules, and a policy enforcement point (PEP) acts on the result.
Why do in-service authorization checks drift as services multiply?
In most codebases, authorization starts as a few lines next to the handler. A web middleware rejects requests whose token lacks an admin role. A decorator such as @requires_role("billing:write") wraps an endpoint. Deeper down, an ORM query filter appends WHERE tenant_id = :current_tenant so a user only ever loads their own rows. Each of these is an enforcement point and a decision point in one place, which is why this approach feels fast and obvious at first.
The trouble starts when the second, fifth and twentieth service each make their own copy. RBAC logic gets duplicated across languages and frameworks, and every copy changes on its own schedule. A fix to how expired roles are handled lands in the orders service but not in invoicing. Role names also start to mean different things. editor can update any document in one service and only the user's own drafts in another, because two teams read the same ticket differently. Nothing fails loudly. Both services pass their own tests.
The deeper cost is auditability. When security asks "who can issue refunds?", no single artifact answers it. The answer is spread across decorators, query scopes and config files in many repositories, and the only way to get it is to read all of them.
None of this means every team needs OPA. If you run a few services in one language and your roles are a short, stable list, a shared authorization library gives you one implementation, one place to review, and no new runtime component to operate. That is often cheaper and clearer. Revisit the decision once the library has to be ported to other languages or teams start forking it.
from functools import wraps
class Forbidden(Exception):
pass
def requires_role(role):
# Decorator: decision and enforcement live together, next to the handler
def wrap(handler):
@wraps(handler)
def inner(user, *args, **kwargs):
if role not in user.roles:
raise Forbidden(f"missing role {role}")
return handler(user, *args, **kwargs)
return inner
return wrap
def scoped_documents(session, Document, user):
# ORM query filter: tenant isolation hidden inside data access
q = session.query(Document).filter(Document.tenant_id == user.tenant_id)
# 'editor' here means: may edit ANY document in the tenant
return q
@requires_role("billing:write")
def issue_refund(user, order_id, amount):
... # refund logic
def can_edit(user, doc):
# 'editor' here means: may edit only the user's OWN drafts.
# Same role name, different semantics, and both services pass their tests.
return ("editor" in user.roles
and doc.owner_id == user.id
and doc.status == "draft")
Two services each implement their own decorator and query-filter checks, showing how the same role name drifts to different meanings with no single place to audit.
How does Open Policy Agent make authorization decisions?
OPA separates the decision from its enforcement. The service, sidecar, or gateway builds a JSON input document describing the request and asks OPA a question such as "is this allowed?" OPA evaluates Rego policy against that input plus any data it has loaded, and returns a JSON decision. OPA blocks nothing itself. The caller must enforce the answer, and a caller that ignores or misreads the response bypasses the policy.
A minimal RBAC policy defaults allow to false. It sets allow to true only when a role held by the subject grants the requested method on the requested path. For an input carrying sub: "u-42", method: "DELETE" and path: ["invoices", "981"], OPA looks up u-42's roles in data. If one of them is billing-admin and that role grants DELETE on invoices, the decision is {"allow": true}.
The split between input and data matters:
- Input holds per-request facts the caller already has: verified token claims, path, and method.
- Data holds facts that change independently of any single request, such as role mappings and tenant membership.
This split is also where staleness comes from. Each OPA instance holds its own copy of data and refreshes it on its own schedule. When you revoke a role, the instances do not all stop granting it at the same moment. Each one keeps allowing the old access until its next refresh. That stale-decision window is the freshness problem, and you need to decide how long a window you can tolerate.
Rego is declarative and takes time to learn. If only the platform team can read the policies, service owners cannot review the rules that govern their own endpoints.
package httpapi.authz
import rego.v1
default allow := false
allow if {
some role in data.user_roles[input.sub]
some grant in data.role_grants[role]
grant.method == input.method
grant.resource == input.path[0]
}
{"user_roles": {"u-42": ["billing-admin"]},
"role_grants": {"billing-admin": [{"method": "DELETE", "resource": "invoices"}]}}
{"input": {"sub": "u-42", "method": "DELETE", "path": ["invoices", "981"]}}
{"result": {"allow": true}}
A minimal Rego RBAC policy with the data OPA loads (role mappings and grants), the per-request input the caller sends, and the decision OPA returns for the caller to enforce.
How does OPA-based authorization work end to end?
Putting the pieces together, a single authorized request in an OPA setup moves through these steps:
- Identity is verified first. The gateway or the service validates the caller's token (signature, expiry, audience). OPA should receive claims that have already been verified, not a raw token it is expected to trust blindly. Rego has built-in functions for decoding and verifying JWTs if you choose to verify inside the policy, but the caller then still needs to pass the token and the verification keys.
- The enforcement point builds the input. The service or proxy assembles a JSON document with the subject, action, resource identifier, and any context it already holds, such as the HTTP method and path or a tenant ID from the URL.
- The enforcement point queries OPA. For a sidecar or central service this is an HTTP
POSTto the Data API path that matches the policy package, as in the/v1/data/httpapi/authzexample above. For the embedded Go library it is an in-process function call. - OPA evaluates the policy. It combines the input with the policy and data from its most recently loaded bundle, and returns a JSON result. Rules with a default value, such as
default allow := false, always produce an answer; rules without one can come back undefined, which the caller must treat as a deny. - The enforcement point acts on the result. It forwards the request or returns a 403. If the decision includes extra fields, for example a list of fields to redact, the service applies them.
- OPA records the decision. If decision logging is enabled, OPA emits a record with the input, the result, and the bundle revision.
- Policy and data update in the background. Each OPA instance polls a bundle server and swaps in new policy and data without a restart. Application code does not change when a rule changes.
The service owns steps 1, 2, 3 and 5. OPA owns steps 4, 6 and 7. That boundary is the whole design: services stop containing authorization rules and start containing a uniform call to a decision point.
Which OPA deployment topology should you use for microservices?
Where OPA runs determines what an outage takes down, how much each decision costs, and how fresh policy and data are at each decision point.
Sidecar / host daemon:
client -> [service] --localhost--> [OPA] decide: OPA enforce: service
Embedded Go library:
client -> [service + OPA in-process] decide + enforce: service process
Central OPA service:
client -> [service] --network--> [OPA cluster] decide: OPA enforce: service
Gateway / mesh:
client -> [gateway or proxy] --> [OPA] decide: OPA enforce: proxy
| allow
v
[service]
| Topology | Latency | Availability dependency | Operational overhead | Data distribution |
|---|---|---|---|---|
| Sidecar / host daemon | Local hop, low | Fails with its pod or host | One OPA per pod or node to run and monitor | Every instance pulls bundles |
| Embedded library | Function call, lowest | Shares the service's fate | Library upgrades ship with each service release | Each process loads bundles |
| Central service | Network hop on every decision | Shared dependency for all callers | One cluster, but it must be highly available | Few copies, easy to keep fresh |
| Gateway / mesh | One hop at the edge or proxy | Proxy and OPA together | Reuses existing proxy infrastructure | Only request attributes are visible |
The sidecar is the common default. It keeps decisions local without requiring every team to build against a Go dependency. The embedded library only suits Go services. It also ties policy engine upgrades to application deploys. A central service makes data easy to manage, but it puts a network round trip and a shared failure domain on every request.
Gateway or mesh enforcement works well for coarse checks such as route, method and caller identity. It cannot see resource state that only the service loads, such as the owner of a record. For that reason, most teams pair it with a second decision point inside or beside the service.
1) Sidecar / host daemon
client --> +-----------+ localhost +-------+
| service |---------->| OPA | decide: OPA
| |<--allow---| local | enforce: service
+-----------+ +-------+
2) Embedded Go library
client --> +------------------------+
| service process | decide: OPA library
| [app] -> [OPA lib] | enforce: service
| in-process call | (same process)
+------------------------+
3) Central OPA service
client --> +-----------+ network +-------------+
| service |---------->| OPA cluster | decide: OPA
| |<--allow---| (shared) | enforce: service
+-----------+ +-------------+
4) Gateway / mesh
client --> +-----------+ +-------+
| gateway / |---------->| OPA | decide: OPA
| proxy |<--allow---| | enforce: proxy
+-----+-----+ +-------+
| allowed requests only
v
+-----------+
| service |
+-----------+
Request paths for four OPA deployment topologies, showing where the policy decision is made and which component enforces it.
What should stay in-service instead of moving to OPA?
A workable split puts rules in OPA when they can be decided from the request and identity alone, and keeps rules in the service when they depend on rows only that service owns. Tenant isolation, coarse RBAC, service-to-service allowlists and admin-only routes belong in OPA. These rules are the same across services, and they are where drift does the most damage. Ownership checks such as "is this user the author of this invoice" stay in-service, because the answer is in the service's database. Put them behind a shared helper or a documented contract so every team applies the same semantics.
Listing data is harder. A yes/no decision answers "can X read document 42". It does not answer "which documents can X see". Calling OPA once per row after fetching a page is slow and breaks pagination. So the filter usually remains a WHERE clause in the service. OPA's partial evaluation can compile a policy into residual conditions that you translate into a query. That works, but it adds a translation layer you have to maintain and test.
The other option is to push resource data into OPA, such as ownership maps and group memberships, so it can decide everything. That gives you one place to read policy. The cost is replication lag and memory growth, and that lag can produce stale denials or stale grants. Splitting logic keeps data fresh but spreads policy across two places.
| Rule type | Where it lives | Reason |
|---|---|---|
| Tenant isolation | OPA | Cross-cutting, decided from identity claims |
| Role-to-route RBAC | OPA | Uniform, changes centrally |
| Service-to-service allowlist | OPA | Depends only on caller identity |
| Admin-only endpoints | OPA | Coarse, route-based |
| Record ownership | In-service | Needs the service's own data |
| List/search filtering | In-service (or partial evaluation) | Must become a query predicate |
| Field-level redaction | In-service | Applied while shaping the response |
How do you implement policy as code with OPA safely?
Treat Rego like any other production code. Keep policies in version control next to their tests. Require the same review process you use for application code, and include an owner from the team whose service a rule protects. A one-line change to a roles lookup can widen access across every caller, so it deserves a careful diff review.
Write unit tests for each rule. In a Rego test file, every rule whose name starts with test_ is a test. Each test sets a fixed request with with input as {...} and asserts whether allow is true or false. Cover the denial paths as thoroughly as the grants: wrong tenant, expired role, missing claim. Run opa test ./policy -v in CI and block merges on failure. opa test --coverage shows which rules no test exercises.
Distribute the result as a bundle. OPA instances poll a bundle server and load new policy without a restart. That decoupling is the main operational benefit: you can revoke a permission in minutes without redeploying a dozen services. It also means one bad bundle reaches every service at once. Version each bundle by setting a revision in its manifest, and sign bundles so instances reject tampered ones. Roll changes out gradually, first to a canary group of instances, and watch decision logs for a jump in denials. Keep the previous revision ready so you can revert quickly.
The investment pays off in reuse. Suppose a tenant-isolation rule is written and tested once. Under in-service checks, the same rule would be re-implemented and audited separately in each language and repository. With a shared policy, an auditor reviews one tested file, not twenty slightly different ones.
cat > policy/authz_test.rego <<'EOF'
package authz_test
import data.authz
test_allow_same_tenant_read if {
authz.allow with input as {
"user": {"tenant": "acme", "roles": ["reader"]},
"action": "read",
"resource": {"tenant": "acme"},
}
}
test_deny_cross_tenant if {
not authz.allow with input as {
"user": {"tenant": "acme", "roles": ["reader"]},
"action": "read",
"resource": {"tenant": "globex"},
}
}
test_deny_missing_roles_claim if {
not authz.allow with input as {
"user": {"tenant": "acme"},
"action": "read",
"resource": {"tenant": "acme"},
}
}
EOF
opa test ./policy -v
opa test ./policy --coverage
A Rego test file that checks both a grant and two denial paths for a tenant-isolation rule, run with opa test in verbose and coverage modes as a CI gate.
Should authorization fail open or closed, and how do you audit decisions?
That review only matters if every request actually reaches the policy. When OPA cannot answer, the enforcement point decides what happens, and that choice should be explicit in configuration, not left to whatever an HTTP client library does on error.
Fail-closed treats a timeout, connection error, or malformed response as a deny. Data stays protected, but authorization becomes a hard dependency. An OPA outage, or a bundle that compiles but denies everything, becomes a service outage. Fail-open keeps traffic flowing but silently removes authorization at the moment you are least likely to notice. For most data-bearing APIs, fail-closed is the defensible default. Fail-open, if used at all, should be limited to low-risk reads and should raise an alert every time it triggers.
Set a short, explicit timeout at the enforcement point. A local sidecar should respond in milliseconds, so a budget much longer than that mostly converts an OPA problem into stalled request threads.
Decision logging
OPA can emit a decision log for each query. The log records the input, the result, and the bundle revision that produced the result. With the revision, you can answer "why was this allowed last Tuesday?" by replaying the input against the exact policy that ran. Without it, you can only guess.
Inputs often carry bearer tokens, emails, and request bodies. Use a masking policy to strip or hash these fields before logs leave the host. Treat the log stream as sensitive data anyway.
The cost is real. One log record per authorization check, kept for a compliance retention period, can add up to more storage than the application's own logs. Budget for sampling allowed decisions, keeping every deny, and enforcing retention limits.
How can OPA save engineering time?
The time savings come from doing cross-cutting authorization work once instead of once per service. They show up in four places:
- Rule changes. Changing a shared rule, such as how tenant isolation treats a support role, becomes one policy change with one set of tests and one review, rolled out as a bundle. Without OPA, the same change is a coordinated edit, test, review and deploy in every service that carries a copy, often in several languages.
- Audits and access reviews. "Who can issue refunds?" becomes a question you answer by reading one policy repository and its tests, and by querying decision logs. You no longer reconstruct the answer by searching decorators and query scopes across repositories.
- Incident investigation. Decision logs with bundle revisions let you replay a specific request against the policy that was live at the time. That replaces guessing which version of which service's check was deployed when the incident happened.
- New services. A new service integrates with the existing decision point and inherits tested rules for tenancy, roles and service-to-service access. It does not need its own port of an authorization library.
As an illustrative estimate, not a measured result, take these assumed inputs: 12 services in 3 languages each carry their own copy of a tenant-isolation rule, and changing that rule takes an assumed half day per service to edit, test, review and deploy. A single rule change then costs about 6 engineer-days, plus coordination across 12 release schedules. With the rule in OPA, assume 1 day to change the policy and its tests and another half day to roll out through a canary, for about 1.5 engineer-days. At an assumed four such changes a year, that is roughly 24 engineer-days against roughly 6. Your numbers will differ. Count your own services, languages and rule-change frequency before relying on this kind of comparison.
The savings have a price. Someone has to run the bundle pipeline, the OPA instances and the decision-log storage, and teams have to learn Rego. If that ongoing cost exceeds the time you save on rule changes and audits, which is likely with a few services and stable roles, the shared library from earlier is the better use of engineering time.
Who should use OPA for microservice authorization?
OPA fits organizations where these conditions hold:
- Many services share the same rules. Tenant isolation, role-to-route mappings and service-to-service allowlists repeat across a large number of services, often written in more than one language.
- A platform or security team can own the policy pipeline. Someone is accountable for the bundle server, signing, rollout, OPA versions, and decision-log retention.
- Auditors or compliance requirements ask for one source of truth. You need to show, test and version authorization rules separately from application code.
- Policy changes on its own schedule. Rules tighten or loosen because of compliance or business changes, not only when a service ships.
- Service teams are willing to read and review Rego. Without this, policy becomes a platform-team black box, and the people who know the business rules cannot check them.
Within those organizations, the people who touch it day to day are platform engineers who run OPA and the bundle pipeline, security engineers who write and review cross-cutting policy, and service developers who integrate the enforcement point and keep data-dependent checks in their own code.
Teams that run a few services in one language with a short, stable list of roles, or that have no one to own the operational pieces, should start with a shared library and revisit OPA when the conditions above start to apply.
When should you avoid OPA, and what does each approach cost?
OPA pays off when the number of services makes "the same rule, implemented N times" a real risk. Three signals point toward centralizing. First, many services enforce overlapping rules. Second, auditors need one place to read and test policy. Third, policy needs to change on a different schedule from application deploys, for example when a compliance rule tightens. In that situation a single policy bundle, tested and versioned once, costs less than tracking down every copy of a rule.
Avoid OPA when you run a handful of services with simple RBAC, or when no platform team will own the bundle pipeline, the sidecars and the decision logs. Without an owner, OPA turns into another unmaintained dependency in the request path, and that is worse than a well-tested library.
| Approach | Development cost | Operational cost | Auditability | Consistency | Team skill requirements |
|---|---|---|---|---|---|
| In-service checks with a shared library | Low at first; rises as each language needs its own port | Low; no extra runtime | Weak; decisions are scattered across service logs | Depends on teams upgrading the library | Each service team's existing language |
| Gateway-only authorization | Low | Low to moderate; the gateway already exists | Good for coarse decisions, blind to resource-level checks | High at the edge, absent inside the mesh | Gateway configuration |
| OPA hybrid (coarse rules in OPA, data-dependent checks in-service) | Moderate; Rego plus integration work | Moderate to high: bundles, agents, decision-log storage | Strong for centralized rules | High for shared rules | Rego, policy testing, platform ownership |
The hybrid is usually where larger organizations settle. It puts the cost of OPA on the rules that benefit from central control and leaves ownership checks next to the data they depend on.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to microservice authorization opa, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.