Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / CAP / Authorization & Security – Roles, Restrictions, XSUAA / IAS

Authorization & Security – Roles, Restrictions, XSUAA / IAS

CAP · SAP BTP ·

Open the interactive lesson →
  1. Why: who is calling, and what may they do?
  2. Authentication and the CAP user
  3. @requires and @restrict
  4. Instance-based authorization: only my region
  5. XSUAA: from CDS roles to role collections
  6. IAS + AMS: the newer option
  7. Other security duties in a CAP app
  8. Testing authorization with mock users
  9. Interview questions

How the Order Approval Portal protects its data (CR7): authentication strategies and the CAP user, pseudo roles, @requires and @restrict, instance-based filters with user attributes, XSUAA with generated xs-security.json and role collections, IAS + AMS as the newer option, other security duties, and testing with mock users.

Part 1 – Why: who is calling, and what may they do?

Requirements on this page

CR-ID

Requirement

Where on the page

CR7

Only logged-in users; reps use RepService, managers ManagerService

Part 2 (authentication), Part 3 (@requires)

CR7

Only managers approve or reject

Part 3 (@restrict grants on actions)

CR7

Reps see only requests of their own region

Part 4 (instance-based, $user attributes)

CR7

Runs with SAP BTP identity services

Part 5 (XSUAA), Part 6 (IAS + AMS)

CR12 (part)

Prove it with tests

Part 8 (mock users, tests)

Two questions decide every request: authentication – who is calling (a valid token, a mock user locally)? – and authorization – may this user perform this event on these rows? In ABAP the answers come from SU01, PFCG roles, authorization objects and DCL. In CAP, authentication is done by a pluggable strategy (XSUAA, IAS, mocked …) that produces a cds.User with roles and attributes; authorization is declared in CDS with @requires and @restrict and enforced by the generic handlers.

CR7 decision flow: token or mock user becomes cds.User with roles and attributes; @requires checks the service, @restrict grants the event, the where condition is added to the query; example annotations for RepService and ManagerService and the resulting SQL

OAuth 2.0, JWT, XSUAA and the app router as BTP building blocks are explained on BTP Foundations › 04 · BTP Security Deep Dive. This page is the CAP side: how CAP consumes those tokens and how you model access.

Part 2 – Authentication and the CAP user

2.1 Authentication strategies

cds.requires.auth.kind

Used for

Notes

mocked

Development and tests (default for cds watch)

Predefined and custom mock users, basic authentication with user name

basic

Simple tests with passwords

Not for production

xsuaa

Production with SAP Authorization and Trust Management (XSUAA)

cds add xsuaa (Part 5)

ias

Production with SAP Cloud Identity Services – Identity Authentication

cds add ias; capire recommends IAS for new projects (Part 6)

jwt

Node.js default in production: XSUAA token validation

xsuaa extends it with SAML attributes in req.user.attr

dummy

Temporarily switching off @requires / @restrict in development

Never in production

custom

Own implementation

Rare; e.g. special gateways

  • In production CAP authenticates every service automatically; a public endpoint must be opened explicitly with @requires: 'any' (capire, Automatic Authentication).
  • By default $metadata of a protected service is protected too.

2.2 The CAP user

Property

Node.js

Java

From

ID

req.user.id

userInfo.getName()

token user_name / sub, mock user name

Roles

req.user.is('Manager')

userInfo.hasRole("Manager")

XSUAA scopes, AMS policies, mock

Attributes

req.user.attr.region

userInfo.getAttributeValues("region")

XSUAA attributes, AMS, mock

Tenant

req.tenant

userInfo.getTenant()

token zone / subaccount (11 · Multitenancy)

2.3 Pseudo roles

Pseudo role

Who has it

Use

authenticated-user

Every successfully authenticated user

"Must be logged in"

any

Everybody, also anonymous

Public endpoints

system-user

Technical clients with client-credentials tokens

Machine-to-machine APIs

internal-user

Technical clients of the same identity instance

Calls inside the same app, e.g. between microservices

Pseudo roles are added by the runtime from the type of authentication – administrators never assign them.

Part 3 – @requires and @restrict

Write authorization in its own file (srv/auth.cds) next to the services – separation of concerns, and reviewers find all rules in one place.

// srv/auth.cds
using { RepService }     from './rep-service';
using { ManagerService } from './manager-service';

annotate RepService     with @(requires: 'Rep');         // whole service: role Rep needed
annotate ManagerService with @(requires: 'Manager');

annotate RepService.ApprovalRequests with @(restrict: [
{ grant: 'CREATE', to: 'Rep' },                                  // region checked in a handler
{ grant: ['READ', 'UPDATE'], to: 'Rep', where: (region = $user.region) },
{ grant: 'DELETE', to: 'Rep', where: (region = $user.region and status = 'N') }
]);

annotate ManagerService.ApprovalRequests with @(restrict: [
{ grant: 'READ', to: 'Manager' },
{ grant: ['approve', 'reject'], to: 'Manager', where: (status = 'N') }
]);
annotate ManagerService.Decisions with @(restrict: [ { grant: 'READ', to: 'Manager' } ]);

Part of a privilege

Values

Meaning

grant

'READ', 'CREATE', 'UPDATE', 'DELETE', 'WRITE' (= create, update, delete), action or function names, '*'

Which events are allowed

to

Role names, pseudo roles; omitted = every user that passes @requires

Who

where

CDS condition with element names, $user, $user.<attribute>

On which rows (instance-based, Part 4)

3.1 Rules worth knowing

  • @requires: 'Manager' is a shortcut for @restrict: [{ grant: '*', to: 'Manager' }]; @readonly equals @restrict: [{ grant: 'READ' }] – so a @readonly entity also blocks its bound actions.
  • Several privileges are combined with OR: a user gets everything granted by any matching entry.
  • Service-level and entity-level restrictions both apply; an entity restriction does not lift a service @requires.
  • Restrictions on a domain entity are inherited by projections unless the projection defines its own; auto-exposed and composition children follow the root's rules (capire, Propagation of Restrictions).
  • For draft-enabled entities the draft events are covered by the grants for the active entity (capire, Draft Mode).
  • capire writes conditions in the expression form where: (region = $user.region), which the compiler checks against the model; the older string form where: 'region = $user.region' still works.

Interview tip: be precise about HTTP codes: missing authentication → 401; authenticated but role or grant missing → 403; instance-based filter on READ → the row is simply not returned (or 404 for a single read).

Part 4 – Instance-based authorization: only my region

CR7: reps of region EMEA must never see APAC requests. The where clause of a privilege is turned into a filter that CAP adds to every query on the entity – reads return only matching rows, and updates or deletes of other rows fail. This is CAP's equivalent of a DCL access control on a CDS view.

{ grant: ['READ', 'UPDATE'], to: 'Rep', where: (region = $user.region) }       // attribute from the token
{ grant: '*', where: (createdBy = $user) }                                     // own records
{ grant: 'READ', to: 'Auditor', where: (region = $user.region or $user.region is null) }   // unrestricted
  • User attributes are lists: region = $user.region matches if the row's region is any of the user's values (['EMEA', 'NA']). An empty or missing attribute means no access – unless you write the is null variant above for "unrestricted" users (capire, User Attributes).
  • Supported in where: comparisons with $user attributes, path expressions to associated entities, and exists predicates on association paths (combinable, nestable, no paths inside the filter); exists with a subquery is Java only.
  • For CREATE (no row exists yet) and for unbound actions Node.js supports only static conditions such as $user.level > 2; check region values for new rows in a before handler instead (04 · Custom Logic).

4.1 When a rule cannot be declared

// srv/manager-service.js – programmatic check (registration pattern on 04 · Custom Logic)
this.before('approve', ApprovalRequests, async req => {
const r = await SELECT.one.from(req.subject).columns('netAmount')
if (r.netAmount > 100000 && !req.user.is('SeniorManager'))
return req.reject(403, 'APPROVAL_LIMIT_EXCEEDED')
})

Declare first, code second: declarative rules are visible in the model, enforced for every protocol and show up in generated artefacts such as xs-security.json.

Part 5 – XSUAA: from CDS roles to role collections

With XSUAA (SAP Authorization and Trust Management service) every CDS role becomes an OAuth scope, every $user attribute an XSUAA attribute. xs-security.json carries them, plus role templates; administrators bundle roles into role collections in the BTP cockpit and assign them to users or identity-provider groups.

Two paths: XSUAA – model roles, generate xs-security.json, deploy XSUAA instance, role collections in the cockpit, JWT scopes checked by CAP; IAS + AMS – same CDS roles, cds add ams generates DCL policies, policies assigned in the SAP Cloud Identity Services console, AMS plugin adds roles and filters
cds add xsuaa                         # auth kind xsuaa for production, xs-security.json, MTA resource
cds compile srv --to xsuaa > xs-security.json     # regenerate after adding roles
{
"xsappname": "order-approval",
"tenant-mode": "dedicated",
"scopes": [
{ "name": "$XSAPPNAME.Rep",     "description": "Rep" },
{ "name": "$XSAPPNAME.Manager", "description": "Manager" }
],
"attributes": [ { "name": "region", "description": "region", "valueType": "s" } ],
"role-templates": [
{ "name": "Rep", "scope-references": [ "$XSAPPNAME.Rep" ],
"attribute-references": [ { "name": "region" } ] },
{ "name": "Manager", "scope-references": [ "$XSAPPNAME.Manager" ] }
]
}
  • Simplified example – the generated file may differ by version. If you edit it by hand, keep scope names exactly equal to the CDS role names: CAP checks them at runtime.
  • Role collections can also be predefined in xs-security.json (role-collections) so they appear after deployment; assignment to users stays an administrator task.
  • Attribute values (e.g. region EMEA) are set on the role in the cockpit or mapped from IdP attributes.

5.1 The app router in front

  • Browser users reach the Fiori apps through an app router (standalone @sap/approuter or the managed one of SAP Build Work Zone). It redirects to the login, receives the JWT and forwards it to the CAP service (destination or route with forwardAuthToken).
  • CAP itself never shows a login page; it validates the token on every request. Technical clients call CAP directly with a client-credentials token (pseudo role system-user).
  • Setting up routes, xs-app.json and destinations: BTP Foundations › 04 · Security Deep Dive and 18 · Hands-On; deployment with MTA: CAP › 08 · Databases & Deployment.

Part 6 – IAS + AMS: the newer option

capire recommends starting new projects with SAP Cloud Identity Services – Identity Authentication (IAS): single sign-on and multi-factor authentication, corporate IdP federation, OpenID Connect and user propagation across landscapes. IAS tokens carry identity but no CAP roles, so roles come from the Authorization Management Service (AMS), also part of SAP Cloud Identity Services.

cds add ams                           # adds the AMS plugin (@sap/ams, @sap/ams-dev for local DCL compilation)
# and runs cds add ias if the project is not on IAS yet
// attributes that administrators may use for filters
annotate RepService.ApprovalRequests with @ams.attributes: { Region: (region) };

Step

XSUAA

IAS + AMS

Roles in CDS

@requires / @restrict – the same

@requires / @restrict – the same

Generated artefact

xs-security.json (scopes, attributes, role templates)

DCL schema and base policies (in ams/dcl/ for Node.js, generated at build)

Assignment

Role collections in the BTP cockpit

Policies in the SAP Cloud Identity Services administration console, optionally with filters

Row filters

where with $user.<attribute>

AMS attributes (@ams.attributes) – the AMS plugin injects roles and filters

Runtime

CAP reads scopes from the JWT

CAP AMS plugin evaluates the user's policies per request

  • AMS is transparent to application code – handlers still use req.user.is('Manager').
  • capire notes two limits: authorizations for technical users can't be addressed by AMS policies yet, and IAS authentication is available only for single-tenant applications – a multitenant SaaS app stays on XSUAA.
  • IAS can consume XSUAA-protected services in a cross-consumption mode, which helps when migrating.

Part 7 – Other security duties in a CAP app

Topic

What CAP offers

Where

Input validation

Generic checks, parameterised CQL (no SQL injection through tagged templates)

03 · Services, 04 · Custom Logic

Personal data

@PersonalData annotations, audit logging plugin @cap-js/audit-logging

capire, Data Privacy

Secrets

Service bindings, never in code or package.json

01 · Foundations

Tenant isolation

Tenant from the token, separate HDI containers per tenant

11 · Multitenancy

Principal propagation to S/4HANA

Destinations with OAuth2SAMLBearerAssertion / user exchange, Cloud Connector

09 · Remote Services

Security headers, CSRF

Handled by the app router and OData adapter (CSRF token for modifying requests from browsers)

BTP › 04 · Security

Part 8 – Testing authorization with mock users

// package.json – mock users for development and tests
"cds": { "requires": { "auth": { "[development]": { "kind": "mocked", "users": {
"mia":  { "roles": ["Rep"],     "attr": { "region": ["EMEA"] } },
"raj":  { "roles": ["Rep"],     "attr": { "region": ["APAC"] } },
"lena": { "roles": ["Manager"] }
} } } } }
// test/auth.test.js – runs with vitest, mocha or node --test (jest: being phased out) (12 · Testing)
const cds = require('@sap/cds')
const { GET, POST, expect } = cds.test(__dirname + '/..')

describe('CR7 authorization', () => {
it('rep sees only own region', async () => {
const { data } = await GET('/odata/v4/rep/ApprovalRequests', { auth: { username: 'mia' } })
expect(data.value.every(r => r.region === 'EMEA')).to.be.true
})
it('rep cannot approve', async () => {
const url = '/odata/v4/manager/ApprovalRequests(ID=4f3a…)/approve'   // an ID from the CSV test data
await expect(POST(url, {}, { auth: { username: 'mia' } })).to.be.rejectedWith(/403/)
})
})
  • cds.test lives in @cap-js/cds-test (npm add -D @cap-js/cds-test). Its HTTP methods reject for status codes outside 200–299 (validateStatus), and its expect is Chai with chai-as-promised and chai-subset, so rejectedWith(/403/) and containSubset work.
  • Java: mock users in application.yaml (cds.security.mock.users) and Spring tests with @WithMockUser (05 · CAP Java).

Common mistakes: testing only as an admin mock user; forgetting the region attribute on a mock user (the rep then sees nothing and the test "passes" with an empty list – assert the count); hand-edited xs-security.json whose scope names no longer match CDS roles; relying on a hidden UI button instead of a server-side grant.

Part 9 – Interview questions

Q1. What is the difference between @requires and @restrict?

@requires names the roles needed for a service, entity or action – a shortcut for @restrict: [{ grant: '*', to: … }]. @restrict lists privileges with grant (events), to (roles) and optional where (row filter) for fine-grained and instance-based authorization.

Q2. How does instance-based authorization work in CAP?

The where condition of a privilege, e.g. region = $user.region, is added as a filter to the queries on that entity, so users see and change only matching rows. User attributes come from the token (XSUAA attributes, AMS) or mock users; they are lists, and an empty attribute means no access.

Q3. What are pseudo roles?

Roles the runtime adds from the type of authentication: authenticated-user, any (also anonymous), system-user (client credentials) and internal-user (technical calls within the same identity instance). Nobody assigns them.

Q4. How do CDS roles end up with real users when you use XSUAA?

cds add xsuaa / cds compile srv --to xsuaa generate xs-security.json with a scope per role and role templates; the MTA creates the XSUAA instance from it; administrators build role collections in the BTP cockpit and assign them to users or IdP groups; at runtime the JWT carries the scopes and CAP maps them to roles.

Q5. Why does capire recommend IAS for new projects, and what is AMS for?

IAS offers SSO, MFA, IdP federation, OpenID Connect and cross-landscape user propagation. IAS tokens have no application roles, so AMS provides them: policies (DCL) generated from CDS roles and attributes are assigned in the Cloud Identity Services console, and the CAP AMS plugin injects roles and filters per request.

Q6. Which HTTP status codes do you expect for authorization failures?

401 when the caller is not authenticated, 403 when authenticated but the role or grant is missing; a row excluded by a where filter is just not returned (404 for a single-entity read).

Q7. How do you test authorization locally?

Mocked authentication with custom mock users (roles and attributes) in the development profile; requests with basic auth (curl -u mia:), .http files or cds.test with auth: { username }; assert both allowed and forbidden cases and the number of returned rows.

Q8. When do you check permissions in code instead of annotations?

When the rule needs data or logic the where language cannot express – e.g. an approval limit by amount per manager level or a check against S/4HANA. Use req.user.is() / req.user.attr in a before handler and req.reject(403, …); keep everything else declarative.

Q9. Scenario: a rep in EMEA sees no requests at all after go-live, although data exists.

The where: (region = $user.region) filter gets no attribute value: the role collection or the IdP mapping does not provide region, so the attribute list is empty and CAP grants nothing. Check the JWT (attribute missing), the role's attribute source in the cockpit, and the attribute reference in xs-security.json.

Q10. Scenario: the Approve button is hidden for reps, but a rep calls the approve URL with Postman and it works.

Authorization was only in the UI. Add @requires: 'Manager' to ManagerService and a @restrict grant for approve / reject to Manager (with where: (status = 'N')), redeploy, regenerate xs-security.json if roles changed, and add a test asserting 403 for a rep.

🏠 Start Here · ◀ 06 · Fiori & Draft · 08 · Deployment ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | GTM ABAP | EHS ABAP | HR ABAP | BW | SAP Datasphere | SAP Business Data Cloud | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP