CAP Security
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Every business application has to answer two questions for each request: who is calling, and what may that caller do. Think of an office building. The reception desk checks your badge and learns your name. After that, each door decides for itself whether your badge opens it, and some doors open only for the person who owns the room. CAP works the same way. It separates the badge check, called authentication, from the door rules, called authorization, and it lets you write the door rules as short annotations in the same CDS model that describes your data. This page explains those two layers, shows the annotations @requires and @restrict with their parts grant, to and where, and runs them against the claims service of Example Trading Co. (EX01) with mocked users, so that you see the HTTP answers 401, 403 and 200 and a result that the where condition has filtered. SAP still documents the platform as SAP BTP, and SAP now presents BTP capabilities as part of SAP Business AI Platform. The facts here apply to CAP Node.js 10.2 (@sap/cds 10.2.2, Node.js 22.12 or newer) and CAP Java 5.2 (Java 21 or newer, 25 recommended); the annotations are the same in both runtimes, and the differences are named where they matter. The deployed side, with XSUAA or SAP Cloud Identity Services, runs in SAP BTP and is described on a sibling page.
Before you read
-
CAP Concepts: services, entities, events and the generic providers that enforce the rules on this page.
-
CAP Getting Started: the
db/,srv/andapp/folders and how to start a project. -
Security: XSUAA and Cloud Identity Services: what happens after deployment, where roles are assigned to real users. This page stays on the CAP side of that line.
-
Users, Roles and Authorizations: the ABAP-side counterpart, if you know PFCG roles.
Key terms
-
Authentication: proving who the caller is, for example with a password or a signed token.
-
Authorization: deciding what an already identified caller may do with which data.
-
CAP role: a plain name such as
Employeethat a CDS annotation refers to and that an administrator or a test configuration assigns to a user. -
Pseudo role: a role such as
authenticated-userthat the runtime adds by itself, depending on how the caller logged in. -
Instance-based authorization: a rule that depends on the data row, such as "only claims that you created".
-
Mocked authentication: a built-in login with fixed test users for local development, never for production.
-
XSUAA: the SAP Authorization and Trust Management service that issues the tokens of a Cloud Foundry deployment.
-
Identity Authentication: the SAP Cloud Identity Services service that CAP names as the first choice for new applications.
Authentication and authorization are two steps
SAP’s guide puts the split in one sentence each: authentication reveals who is using the service, and authorization controls how that user may interact with the application’s resources. Authentication has to come first, because the rules need a user to talk about. What links the two is the CAP user, a small object that the runtime builds after a successful login. It carries a logon name, a tenant, the roles the user has and the attributes the user has been given. Your CDS rules and your handler code only ever see this object, never a password or a raw token, and that is why the same model works with a test login on a laptop and with a real identity service in the cloud.
Source: CAP: Authorization, CAP: Authentication and CAP: Users and roles
The authentication strategy is configuration (cds.requires.auth). The authorization rules are part of the model. Keeping them apart lets you develop with fake users and deploy with real ones without touching the rules.
The CAP user and its roles
Three kinds of values on the CAP user matter for the rules.
-
The name is what
$userstands for in a CDS annotation. In a mocked login it is the user name you typed. -
The roles are plain business names such as
Employee. SAP’s guide recommends that they reflect basic operations of the application, and it deliberately speaks of roles instead of OAuth scopes. On XSUAA each CAP role arrives as a scope; the sibling page shows how CAP generates the matchingxs-security.json. -
The attributes are named lists of values, such as a cost center. In a rule they are written
$user.costCenter.
Besides the roles that an administrator assigns, the runtime adds pseudo roles after login, because they describe how the caller authenticated and not what the caller may do for the business.
| Pseudo role | Meaning |
|---|---|
|
Added after any successful authentication. A service annotated with it is closed to anonymous callers and open to every logged-in user. |
|
Applies to everyone. If no caller name is available the name is |
|
A technical caller, recognized in the Node.js runtime by the OAuth grant type client credentials. Its user name is |
|
A technical caller from the application’s own provider tenant, reached with the grant type client credentials and a shared identity instance, as SAP’s guide describes it. It is meant for calls between the parts of one application. |
In custom handler code of the Node.js runtime, a role is checked with req.user.is('Employee'), but SAP’s guide advises leaving this to the CDS model whenever possible.
Source: CAP: Users and roles and CAP Node.js: Authentication
Without annotations, nothing is protected
CAP’s authorization guide states it plainly: by default CDS services have no access control, so without authorization modeling authenticated users have access to all entities, and applications must implement proper authorization. In a non-production profile the Node.js runtime does not even ask for a login at an unrestricted service. The command below ran against an unmodified copy of the claims service of this site’s lab, which has no annotation at all.
curl -s -w '\nHTTP %{http_code}\n' 'http://localhost:4121/odata/v4/expense/Claims?$select=title,amount'
{"@odata.context":"$metadata#Claims","value":[{"title":"Train ticket","amount":"45.50","ID":"11111111-1111-1111-1111-111111111111","IsActiveEntity":true}]}
HTTP 200
Source: CAP: Authorization and CAP: Authentication
The server’s startup log said using auth strategy { kind: 'mocked' }, the default of the development profile. This is convenient on a laptop and a trap in a deployment, which is why the next sections add rules before anything leaves the laptop.
The teaching model
All listings from here on ran for real in a copy of the lab project, with CAP Node.js 10.2 (@sap/cds 10.2.2) on the in-memory SQLite database, served with npx cds-serve on port 4121. Nothing needs an SAP BTP account. The lab models claims as an entity Claims with the aspects cuid and managed, which add the key ID and the elements createdBy, createdAt, modifiedBy and modifiedAt. The element createdBy is the owner of a claim: the runtime fills it with the name of the user who created the row. The service ExpenseService exposes Claims with @odata.draft.enabled.
The rules need two more facts that the lab does not have, so the lab copy adds a teaching model, which is not part of the lab and not SAP software. It is shown here in full. The first file extends the table with a cost center, declares the service level rule and restricts the entity.
using { ExpenseService } from './expense-service';
using { sap.guide.expenses as db } from '../db/schema';
extend db.Claims with { costCenter : String(10); }
annotate ExpenseService with @(requires: 'authenticated-user');
annotate ExpenseService.Claims with @(restrict: [
{ grant: 'CREATE', to: 'Employee' },
{ grant: ['READ', 'UPDATE'], to: 'Employee', where: 'createdBy = $user' },
{ grant: 'READ', to: 'Manager', where: 'costCenter = $user.costCenter' },
{ grant: '*', to: 'Admin' }
]);
Source: CAP: Authorization
The second file is a separate service for auditors that exposes the same table read-only.
using { sap.guide.expenses as db } from '../db/schema';
@path: 'audit'
@requires: 'Auditor'
service AuditService {
@readonly entity AllClaims as projection on db.Claims;
}
Source: CAP: Authorization
The third part is the list of mocked users in the cds section of package.json. Each user has a password and, optionally, roles and attributes. In the Node.js runtime an attribute value is a list.
"cds": {
"requires": {
"[development]": {
"auth": {
"kind": "mocked",
"users": {
"anna": { "password": "anna", "roles": ["Employee"] },
"ben": { "password": "ben", "roles": ["Employee"] },
"mia": { "password": "mia", "roles": ["Manager"], "attr": { "costCenter": ["4711"] } },
"max": { "password": "max", "roles": ["Manager"], "attr": { "costCenter": ["4712"] } },
"ada": { "password": "ada", "roles": ["Auditor"] },
"root": { "password": "root", "roles": ["Admin"] },
"guest": { "password": "guest" }
}
}
}
}
}
Source: CAP Node.js: Authentication and CAP: Authentication
The key [development] limits the users to the development profile. SAP’s guide warns that mocked authentication is not suitable for production and recommends defining mock users in the development profile only. The user guest has a login but no role, which makes it the test case for "authenticated, but not allowed". CAP also ships pre-defined mock users such as alice and bob that are merged with yours.
@requires: who may use a resource
The annotation @requires names the role, or the several roles, that a caller needs for a resource. The resource can be a whole service, an entity, or an action or function. Several roles in a list are alternatives: having one of them is enough. The line annotate ExpenseService with @(requires: 'authenticated-user') above admits every logged-in user and nobody anonymous. The AuditService uses the same annotation with a business role, so only users with Auditor pass. SAP’s guide adds that @requires: 'Viewer' is a shortcut for @restrict: [{grant:'*', to: 'Viewer'}], and that a restricted service also protects its $metadata document and its service root.
The two annotations cover different needs. Use @requires when one role answers the question completely, for a service or an action. Use @restrict as soon as the answer depends on the operation or on the data row.
@restrict: grant, to and where
The annotation @restrict holds a list of privileges. Each privilege has up to three parts, and SAP’s guide gives the general form { grant: <events>, to: <roles>, where: <filter-condition> }.
-
grantnames the events that the privilege covers:READ,CREATE,UPDATE,DELETE, the name of an action or function,WRITEfor all four writing events, or'*'for every event. Several events go in a list. -
tonames the roles, or pseudo roles, that the privilege is for. If you leave it out, it meansany. -
whereis a condition in CQL syntax that narrows the privilege to some rows. It may use columns of the entity, constants, the user name$userand user attributes such as$user.costCenter.
A privilege is met only if all its parts are met. A request passes the restriction if at least one privilege is met, and when several privileges match, their where conditions are combined with OR. Read the entity restriction of the teaching model aloud and it becomes a policy.
-
An
Employeemay create claims. -
An
Employeemay read and update the claims that the user created (createdBy = $user). -
A
Managermay read the claims of the manager’s own cost centers (costCenter = $user.costCenter). Nothing lets a manager write. -
An
Adminmay do everything.
Restrictions can sit on several levels, and the rule is that every check of the hierarchy must pass (logical AND). In the teaching model a caller needs authenticated-user on the service and then one matching privilege on the entity. The service rule is the front door and the entity rule is the door of the room. A restriction on a service entity also replaces whatever it would inherit from the database entity it projects, which is one reason SAP’s guide recommends restrictions on database entities only in exceptional cases. For draft entities the guide derives the draft rules from the normal ones: a user who may CREATE may create a new draft, a user who may UPDATE may put a row into draft mode, and only the creator can edit a draft, so you do not write draft events into the model.
Source: CAP: Authorization
What a where condition does at runtime
The condition is not a check that your code performs. For READ the runtime adds it as a filter to the database query, so rows that do not match never leave the database. For UPDATE and DELETE it is a reject condition. SAP’s guide gives two consequences that you will see in the output below. A request for one row that the filter hides is answered with 404 Not Found and not 403, so that an unauthorized caller cannot learn that the row exists, while an UPDATE or DELETE of such a row is rejected with 403 so that a user interface can tell the cases apart. In the Node.js runtime a condition on CREATE may only be a simple static expression without reference to the model, such as where: $user.level = 2. That is why the teaching model grants CREATE in its own privilege and keeps createdBy out of it. The Java runtime additionally checks the filter against the input data of CREATE and UPDATE and rejects a non-matching input with 400.
Source: CAP: Authorization
Running it: 401, 403 and 200
The server was started with PORT=4121 npx cds-serve. Mocked users use HTTP basic authentication, so curl -u name:password is enough. The first three requests are the three layers of the model.
curl -s -o /dev/null -w "HTTP %{http_code}\n" http://localhost:4121/odata/v4/expense/Claims
curl -s -o /dev/null -w "HTTP %{http_code}\n" -u anna:wrong http://localhost:4121/odata/v4/expense/Claims
curl -s -o /dev/null -w "HTTP %{http_code}\n" -u guest:guest http://localhost:4121/odata/v4/expense/Claims
HTTP 401
HTTP 401
HTTP 403
Source: CAP: Authentication
Without credentials and with a wrong password the caller is not identified, and the answer is 401. The user guest is identified but has no role, passes the service rule authenticated-user, and is refused by the entity restriction with 403.
Because Claims is draft enabled, a claim is created as a draft and then activated, and the owner is whoever created it. The next commands create one claim as anna (cost center 4711) and one as ben (4712). Each user activates their own draft; the shortened output shows only the status of each activation.
curl -s -u anna:anna -H 'Content-Type: application/json' -d '{"title":"Hotel","amount":120,"costCenter":"4711"}' http://localhost:4121/odata/v4/expense/Claims
curl -s -u anna:anna -X POST -H 'Content-Type: application/json' -d '{}' "http://localhost:4121/odata/v4/expense/Claims(ID=<ID of the draft>,IsActiveEntity=false)/ExpenseService.draftActivate"
activate anna: HTTP 201
activate ben: HTTP 201
Source: CAP: Authorization
The lab’s seed row Train ticket has createdBy anonymous, because the seed file does not set it, so the table now holds three claims. The same request, GET /odata/v4/expense/Claims?$select=title,createdBy,costCenter, then gave a different answer to each user. Only the value part of each answer is shown, with the HTTP status after it.
| User | Claims returned | Status |
|---|---|---|
|
|
200 |
|
|
200 |
|
|
200 |
|
|
200 |
|
|
200 |
The raw answer of anna was the following, unchanged apart from the key order that the runtime chose.
{"@odata.context":"$metadata#Claims","value":[{"title":"Hotel","createdBy":"anna","costCenter":"4711","ID":"6ad4386f-adcd-4914-905e-a8acb4c29535","IsActiveEntity":true}]}
Source: CAP: Authorization
All five calls hit the same URL, and the data is filtered by who asks. Nobody wrote an if or a WHERE clause: the rows are the result of the where conditions. A second round addressed single claims and writes, with the claim of anna as the target.
| Request | Caller | Status |
|---|---|---|
|
|
200 |
|
|
404 |
|
|
404 |
|
|
403 |
|
|
403 |
|
|
403 |
|
|
204 |
The two 404 answers are the filter at work, and the 403 answers are the missing privileges: ben has UPDATE, but not on this row, and mia has no write privilege at all. The AuditService behaves as a @requires service should.
| Request | Caller | Result |
|---|---|---|
|
|
200 with all claims |
|
|
403, message |
|
no credentials |
401 |
|
|
405, message that the entity is read-only |
|
|
403, because the entity restriction names no privilege for her role |
Source: CAP: Authorization
The last row is worth a second look: roles do not carry over between services. The auditor reads everything through AuditService and nothing through ExpenseService, because each resource lists the roles it admits.
Rules in tests
Security rules deserve tests, and mocked users make them cheap. SAP’s guide says that unit tests for security are essential and that integration tests in the production profile should check that unauthenticated users cannot reach any endpoint. With cds.test the credentials go with each request through the auth option. The test file below ran with npm test, which calls node --test.
import cds from '@sap/cds'
import { test } from 'node:test'
import assert from 'node:assert'
const { GET } = cds.test(import.meta.dirname + '/..')
const as = (username, password = username) => ({ auth: { username, password } })
const status = promise => promise.then(r => r.status, e => e.status ?? e.response?.status)
test('anonymous requests are rejected', async () => {
assert.equal(await status(GET('/odata/v4/expense/Claims')), 401)
})
test('a user without roles is refused', async () => {
assert.equal(await status(GET('/odata/v4/expense/Claims', as('guest'))), 403)
})
test('an employee sees only own claims', async () => {
const { data } = await GET('/odata/v4/expense/Claims', as('anna'))
assert.ok(data.value.every(c => c.createdBy === 'anna'))
})
test('an admin sees all claims', async () => {
const { data } = await GET('/odata/v4/expense/Claims', as('root'))
assert.ok(data.value.length >= 1)
})
test('only an auditor reads the audit service', async () => {
assert.equal(await status(GET('/odata/v4/audit/AllClaims', as('anna'))), 403)
assert.equal(await status(GET('/odata/v4/audit/AllClaims', as('ada'))), 200)
})
All five tests of this file passed. The test lists claims of the original lab, which calls the service without credentials, failed with 401 - Unauthorized, which is correct: the lab test was written for an unprotected service, and a protected service needs a user in that test too. Whenever you add rules to a project, update its older tests the same way.
Authentication strategies
The strategy decides how the CAP user is created. It is chosen with cds.requires.auth, and cds env get requires.auth prints the effective value of the current profile.
| Strategy | What it does |
|---|---|
|
Creates a user that passes every authorization check. SAP describes it as a way to switch the |
|
Basic authentication with fixed test users, the default of the development profile. |
|
Reads the user, the roles and the attributes from a signed token in the |
|
An extension of |
IAS with AMS |
For SAP Cloud Identity Services. SAP’s guide recommends starting new projects with Identity Authentication and explains that its tokens carry only static user information, so the Authorization Management Service (AMS) delivers the CAP roles and the filter values through policies. |
Running npx cds env get requires.auth --profile production in the lab copy printed the kind jwt and the label xsuaa for the service binding, so a profile switch is all that separates the mocked login of a laptop from token validation. In production, SAP’s Node.js guide says that every service of a project with a configured strategy is authenticated by default, and a service without @restrict or @requires implicitly gets @requires: 'authenticated-user'. That default does not replace the rules above: it only closes the door to anonymous callers.
In CAP Java the annotations are the same, and the mocked users are configured in application.yaml instead of package.json. The listing below is SAP’s example for the Java runtime. It requires a CAP Java project; not run here.
spring:
config.activate.on-profile: default
cds:
security:
mock:
users:
viewer-user:
tenant: CrazyCars
roles:
- Viewer
attributes:
Country: [GER, FR]
Source: CAP: Authentication
For a CAP Java project, SAP states that its Maven dependencies enable the authentication middleware, and that the platform starter bundles for Cloud Foundry and Kubernetes bring them. The sibling page Security: XSUAA and Cloud Identity Services covers the deployed side: where the roles are assigned to real users and how the identity provider is trusted.
Pitfalls
-
Rules are not automatic. SAP’s guide says CAP cannot enforce authorization automatically, because it depends entirely on your domain model. A service without annotations is open to every authenticated user.
-
Do not rely on the application router. SAP’s authentication guide lists as a pitfall that the application router as a front proxy does not shield the backend from incoming traffic, so the backend must be secured independently.
-
Mocked users are for development. Define them in the development profile only, and test in the production profile that anonymous requests are rejected.
-
Keep the filters in custom code. If a handler changes or extends a query, SAP’s guide asks you to make sure that the authorization filters stay in it.
-
Know the limits of the Node.js runtime. The guide says that restrictions are evaluated on the target entity of the request only. Expanded entities of a
READand the parts of a deep insert or update are not checked against their own restrictions, and the guide gives solution sketches. The Java runtime checks associated entities, but not restrictions on composition children. -
Avoid guessable keys. A hidden row answers 404 and a forbidden write answers 403, so a key that can be enumerated efficiently reveals which rows exist. SAP’s guide suggests keys that are not enumerable.
Source: CAP: Authorization and CAP: Authentication
Summary
-
Authentication finds out who calls, and the result is the CAP user with a name, roles and attributes. Authorization is declared in the CDS model and enforced by the runtime.
-
@requiresnames the role that a service, an entity or an action needs.@restrictlists privileges withgrant,toandwhere: one met privilege is enough, and every level of the hierarchy must pass. -
A
wherecondition such ascreatedBy = $userfilters the rows of a read and rejects writes, so it gives each user a different result from the same request, with 404 for hidden rows and 403 for forbidden writes. -
Test both refusals, 401 for unknown callers and 403 for known callers without a matching privilege, with mocked users locally and again in the production profile.
-
Mocked users are for development. In production the strategy is
jwt, in practice with XSUAA or with Identity Authentication and AMS, and the same rules apply unchanged.
Try it
To do this by hand, follow the guide Secure a CAP Service with Roles: it protects a service with roles and shows the 401 and 403 answers.