SAP Guide: Secure a CAP Service with Roles

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Checked on 2026-11-13 against CAP Node.js 10.2 (@sap/cds 10.2.2, @sap/cds-dk 10.2.1, @cap-js/cds-test 1.0.2), curl and Node.js 24.21.

What you build

This is a teaching model built with CAP. It is not SAP S/4HANA or SAP SuccessFactors and does not reproduce their screens.

You build a small service for expense claims that anybody can read and change, and then you close it. Two short annotations say that every caller must be logged in, that every logged-in user may read the claims, and that only a user with the role admin may create, change or delete a claim or approve it. You then call the service as the users that CAP ships for development: alice, who has the role admin, and bob, who has not. You see the answers 401 (not logged in), 200 (allowed), 403 (logged in but not allowed) and 204 (an action ran), and you write four tests that keep the rules in place. Nothing is deployed and no real user is involved. How the same roles reach a service in production is explained in the text after the steps.

Terminal after npm test: four tests pass, named without a login the answer is 401, alice and bob may read, bob may not change a claim and alice may, and only alice may approve; the summary lists tests 4, pass 4 and fail 0

Before you start

  • No account is needed: the CAP tools install from the public npm registry without signing in, and the users in this guide are test users that CAP carries inside the runtime. Installing @sap/cds-dk and @sap/cds means accepting the SAP Developer License Agreement, version 3.2, which the packages state themselves; the lab README names it. No password is typed anywhere: the built-in users have none.

  • Install Node.js 22.12 or newer and the CAP command line tools (npm install --global @sap/cds-dk). Use a code editor and two terminals, one for the server and one for the calls. The curl command comes with macOS and current versions of Windows and Linux.

  • The guide Your First CAP Service builds the same kind of project with the same commands. If you have not done it, read its steps first or at least know what an entity, a service and cds watch are. The project here is new, so you need nothing from that guide.

  • Read CAP Security for the full story of @requires, @restrict and where conditions; this guide only uses the simplest rules. Security: XSUAA and Cloud Identity Services covers what happens after deployment.

  • The figures are drawings of the editor and the terminal, not screenshots. A highlighted box with a number marks the file or the command of the step with the same number. The server runs on port 4004 in the figures and in the text; if another program already uses that port, cds watch tells you which port it took, and you use that port in the addresses.

  • The names are the lab’s own: the entity Claims, the service ClaimsService, the action approve and the claim Train ticket are made up for this guide. The role admin and the users alice and bob come from CAP.

Steps

Create the project

  1. Create the project and install its dependencies. The option --nodejs chooses the JavaScript runtime of CAP.

    cds init claims-secured --nodejs
    cd claims-secured
    npm install
  2. Create the file db/schema.cds. The aspect managed makes CAP fill createdBy and modifiedBy with the name of the user who calls the service, which later shows who changed a claim.

    using { cuid, managed } from '@sap/cds/common';
    namespace sap.guide.secured;
    
    entity Claims : cuid, managed {
      title  : String(80);
      status : String(1) default 'N';
      amount : Decimal(9,2);
    }
  3. Create the folder db/data and in it the file sap.guide.secured-Claims.csv, which CAP loads into the in-memory database when the server starts:

    ID,title,status,amount
    11111111-1111-1111-1111-111111111111,Train ticket,N,45.50
    22222222-2222-2222-2222-222222222222,Hotel,N,120.00
  4. Create the file srv/claims-service.cds. It offers the entity as an OData service and declares an action approve that works on one claim. At this point the service has no security rule at all.

    using { sap.guide.secured as db } from '../db/schema';
    
    service ClaimsService {
      entity Claims as projection on db.Claims actions {
        action approve();
      };
    }
  5. Create the file srv/claims-service.js. CAP loads a file with the same name next to the model file as the implementation of the service. The handler runs when the action is called and sets the status of the claim to A (approved). It contains no check of who the caller is, because the rules in the model decide that before the handler runs.

    import cds from '@sap/cds'
    
    export default class ClaimsService extends cds.ApplicationService {
      init() {
        this.on('approve', 'Claims', async req => {
          const { ID } = req.params[0]
          await UPDATE('sap.guide.secured.Claims', ID).with({ status: 'A' })
        })
        return super.init()
      }
    }
    Visual Studio Code with the claims-secured project: the explorer lists the folders app, db and srv, the CSV file and schema.cds in db, the files claims-service.cds and claims-service.js in srv and package.json; the editor shows srv/claims-service.cds with the service ClaimsService, the entity Claims as a projection on db.Claims and the action approve; the terminal shows cds init with the option nodejs and npm install ending in found 0 vulnerabilities; callout 2 marks schema.cds, callout 3 the CSV file, callout 4 the service file and callout 5 the handler file

Run the service without rules

  1. In the first terminal, in the project folder, start the server:

    cds watch

    The log ends with server listening on { url: 'http://localhost:4004' }. Read the line using auth strategy { kind: 'mocked' }: the server is in the development profile, where CAP checks logins against a built-in list of test users instead of a real identity service. The service is served at /odata/v4/claims.

    Terminal after cds watch: the log lists the model files srv/claims-service.cds, db/schema.cds and the common.cds of CAP, connects to an in-memory SQLite database, initializes it from db/data/sap.guide.secured-Claims.csv, shows the line using auth strategy kind mocked, serves ClaimsService at /odata/v4/claims with the implementation srv/claims-service.js and ends with server listening on http://localhost:4004; callout 6 marks the command

    The figure leaves out the banner that cds watch prints before the first line.

  2. In the second terminal, store the two addresses that the next calls use, then read one claim without any credentials. The $ in $top and $select is escaped with a backslash so that the shell does not read it as a variable.

    BASE=http://localhost:4004/odata/v4/claims/Claims
    CLAIM="$BASE(11111111-1111-1111-1111-111111111111)"
    curl -s -w '\nHTTP %{http_code}\n' "$BASE?\$top=1&\$select=title"

    The answer is the claim and HTTP 200.

  3. Now change the claim, again without credentials. The -X PATCH option sends an update and -d carries the new amount.

    curl -s -o /dev/null -w 'HTTP %{http_code}\n' -X PATCH \
      -H 'Content-Type: application/json' -d '{"amount":50}' "$CLAIM"

    The answer is HTTP 200 again: anyone who can reach the service can change the data. CAP’s authorization guide says that services have no access control unless you model it, and in development it does not even ask for a login. That is the state the next steps fix.

    Terminal with two curl calls to the service before any rule exists: the first, a read without credentials, answers HTTP 200 with the claim Train ticket; the second, a PATCH that sets the amount to 50 without credentials, also answers HTTP 200; callout 7 marks the read and callout 8 the write

    The figure shows each command on one line; the page wraps the long one with a backslash.

Add the rules

  1. Create the file srv/claims-access.cds. It does not touch the service file: the keyword annotate adds the rules from outside. The first rule, @requires: 'authenticated-user' on the service, admits every logged-in user and nobody else. The second, @restrict on the entity, is a list of privileges. A privilege has the events it covers (grant) and the roles it is for (to). Reading is for every logged-in user, and the writing events and the action approve are for the role admin.

    using { ClaimsService } from './claims-service';
    
    annotate ClaimsService with @(requires: 'authenticated-user');
    
    annotate ClaimsService.Claims with @(restrict: [
      { grant: 'READ', to: 'authenticated-user' },
      { grant: ['CREATE', 'UPDATE', 'DELETE', 'approve'], to: 'admin' }
    ]);
  2. Save the file. cds watch notices the new file and restarts. The log now lists four model files, with srv/claims-access.cds among them, and the server listens again. From here on every answer depends on who calls.

    Visual Studio Code with the new file srv/claims-access.cds open: it annotates ClaimsService with requires authenticated-user and the entity ClaimsService.Claims with a restrict list that grants READ to authenticated-user and grants CREATE, UPDATE, DELETE and approve to admin; the terminal shows the restart of cds watch, which now loads four model files and lists srv/claims-access.cds first; callout 9 marks the file in the explorer and callout 10 marks the terminal

Call the service as mocked users

CAP ships a list of test users for the development profile. In this guide only two matter: alice has the role admin, and bob has no role that the rules know. You can print the list with cds env get requires.auth. The users have no password. curl -u bob: sends the name and an empty password, and the colon after the name is what tells curl not to ask for one.

  1. Read the claims without credentials, and print only the status line and the header that asks for a login.

    curl -s -i "$BASE" | grep -iE '^(HTTP|www-authenticate)'

    The answer is HTTP/1.1 401 Unauthorized and WWW-Authenticate: Basic realm="Users". 401 means "I do not know who you are". The service rule authenticated-user needs a user, and there is none.

  2. Read as bob:

    curl -s -w '\nHTTP %{http_code}\n' -u bob: "$BASE?\$top=1&\$select=title"

    The answer is HTTP 200 with the claim. bob is logged in, and the first privilege admits every logged-in user to read.

  3. Change a claim as bob:

    curl -s -w '\nHTTP %{http_code}\n' -u bob: -X PATCH \
      -H 'Content-Type: application/json' -d '{"amount":50}' "$CLAIM"

    The answer is the error Forbidden with the code 403 and HTTP 403. 403 means "I know who you are, and you may not do this". bob has no role for the event UPDATE.

    Terminal with three curl calls after the rules: a read without credentials answers HTTP/1.1 401 Unauthorized and a WWW-Authenticate header for Basic realm Users; a read as bob answers HTTP 200 with the claim Train ticket; a PATCH as bob answers the error Forbidden with code 403 and HTTP 403; callout 11 marks the first call, callout 12 the second and callout 13 the third
  4. Make the same change as alice:

    curl -s -o /dev/null -w 'HTTP %{http_code}\n' -u alice: -X PATCH \
      -H 'Content-Type: application/json' -d '{"amount":50}' "$CLAIM"

    The answer is HTTP 200. The role admin is named in the privilege for UPDATE.

  5. Call the action as bob. The path is the claim, a slash, the service name and the action name.

    curl -s -w '\nHTTP %{http_code}\n' -u bob: -X POST \
      -H 'Content-Type: application/json' -d '{}' \
      "$CLAIM/ClaimsService.approve"

    The answer is Forbidden, code 403: the action is in the same privilege as the writing events, so it is for admin only.

  6. Call the same action as alice:

    curl -s -o /dev/null -w 'HTTP %{http_code}\n' -u alice: -X POST \
      -H 'Content-Type: application/json' -d '{}' \
      "$CLAIM/ClaimsService.approve"

    The answer is HTTP 204: the action ran and returns no content.

  7. Read the claim again to see what the handler and the aspect managed did:

    curl -s -u alice: "$CLAIM?\$select=title,status,amount"

    The status is now A and the amount is 50.00. Asking for modifiedBy shows alice, because CAP filled the field from the logged-in user.

    Terminal with four curl calls: a PATCH as alice answers HTTP 200; an approve call as bob answers the error Forbidden with code 403 and HTTP 403; the same approve call as alice answers HTTP 204; a read as alice shows the claim Train ticket with the status A and the amount 50.00; callouts 14 to 17 mark the four calls in order

    The figure shows the long commands with only the end of the address wrapped; in the terminal they are one command each.

  8. Keep the rules in place with tests. Add the test library and a test script to the project; the second command writes the script test into package.json.

    npm add --save-dev @cap-js/cds-test@1.0.2
    npm pkg set scripts.test="node --test"
  9. Create the folder test and in it the file access.test.js. The test starts the service in-process with cds.test. The function as passes a mocked user and an empty password with each call, and validateStatus lets a 401 or 403 come back as an answer instead of an exception.

    import cds from '@sap/cds'
    import { test } from 'node:test'
    import assert from 'node:assert'
    
    const { GET, PATCH, POST } = cds.test(import.meta.dirname + '/..')
    const base = '/odata/v4/claims/Claims'
    const id = '11111111-1111-1111-1111-111111111111'
    const any = { validateStatus: s => s }
    const as = name => ({ auth: { username: name, password: '' }, ...any })
    
    test('without a login the answer is 401', async () => {
      const res = await GET(base, any)
      assert.strictEqual(res.status, 401)
    })
    
    test('alice and bob may read', async () => {
      for (const name of ['alice', 'bob']) {
        const res = await GET(base, as(name))
        assert.strictEqual(res.status, 200)
        assert.strictEqual(res.data.value.length, 2)
      }
    })
    
    test('bob may not change a claim, alice may', async () => {
      const denied = await PATCH(`${base}(${id})`, { amount: 50 }, as('bob'))
      assert.strictEqual(denied.status, 403)
      const done = await PATCH(`${base}(${id})`, { amount: 50 }, as('alice'))
      assert.strictEqual(done.status, 200)
    })
    
    test('only alice may approve', async () => {
      const url = `${base}(${id})/ClaimsService.approve`
      const denied = await POST(url, {}, as('bob'))
      assert.strictEqual(denied.status, 403)
      const done = await POST(url, {}, as('alice'))
      assert.ok(done.status < 300)
    })
  10. Run the tests. The summary names four tests and four passes; the times in parentheses differ on your computer.

    npm test

Check the result

  • A request without credentials answers 401, as bob and as alice it can read, and bob gets 403 for an update and for the action approve.

  • As alice the update answers 200 and the action answers 204; reading the claim afterward shows the status A.

  • npm test ends with pass 4 and fail 0.

From mocked users to production

The rules you wrote do not change when the service is deployed. What changes is the answer to "who is calling", and it changes by configuration, not by code. In the development profile the authentication strategy is mocked: a list of fixed users inside the runtime, with names, roles and no password. In the production profile CAP reads the strategy jwt instead, which cds env get requires.auth --profile production printed in the lab. There the caller sends a signed token, the JSON Web Token (JWT), in the Authorization header, and CAP builds its user from the token: the name, and the roles from the scopes in the token. This is the part that XSUAA, the SAP Authorization and Trust Management service, plays on SAP BTP Cloud Foundry. It issues the tokens, and an administrator of the subaccount decides which user gets which scopes.

A role such as admin in your annotation therefore becomes a scope with the same name. npx cds compile srv --to xsuaa prints the descriptor that CAP generates from the roles in the model (see the first variation below), and cds add xsuaa writes it into the project as xs-security.json. At deployment the descriptor creates the XSUAA service instance. An administrator then bundles the roles into role collections and assigns the collections to users. The users alice and bob do not exist there: a person is admin only if a role collection that holds that role was assigned to the person. SAP now recommends Identity Authentication with the Authorization Management Service for new projects; the reference page names the choice. This guide does none of this, because it needs a deployed application and an SAP BTP account, and the guide needs neither. The full explanation, with the generated file and the role collections, is in Security: XSUAA and Cloud Identity Services.

Variations

  • Print what CAP would generate for XSUAA from the roles of your model. The command only reads the model and prints; it contacts nothing:

    npx cds compile srv --to xsuaa

    The answer lists one scope, $XSAPPNAME.admin, and one role template admin that references it. The role authenticated-user is not a scope, because the runtime adds it after any successful login.

  • Let only the owner change a claim. In claims-access.cds an UPDATE privilege can carry a where condition such as createdBy = $user, which the reference page CAP Security explains.

What can go wrong

Symptom Cause Fix

alice gets Forbidden with code 403 on an update after you changed the role in the file to Admin

Role names are case sensitive. Admin is a different role from admin, and the user alice has only admin.

Write the role exactly as the user has it, here admin, and save; cds watch restarts.

A PATCH answers Unsupported Media Type with code 415

The call has no Content-Type: application/json header.

Add -H 'Content-Type: application/json' to the curl command.

The address answers Invalid resource path "ClaimsService.Claim" with code 404

The entity name in the address has a typo (Claim for Claims).

Copy the address from the variable CLAIM.

A call as alice with a wrong password still answers 200

The built-in users have no password, so the mocked login accepts any password for them. It tests roles, not passwords.

Do not read a 200 here as proof that a password is checked. Real logins come with the production strategy.

Every call answers 401 after the rules were added

The call has no -u option, so there is no user.

Add -u alice: or -u bob:, with the colon.

Clean up

Press Ctrl+C in the first terminal to stop cds watch. The database lived only in memory, so the changed claim is gone at the next start. The project folder is yours to keep.

Where to go next