Describes Authentication and Authorization in CAP Java



With respect to web services, authentication is the act of proving the validity of a presented user claim passed with the request. This typically comprises verifying the request user’s identity, tenant, and additional claims like granted roles. Briefly, authentication controls who is using the service. In contrast, authorization makes sure that the user has the required privileges to access the requested resources. Hence, authorization is about controlling what the user is doing with the service.

Obviously, a proper authorization needs to rely on a processed authentication, which asserts the user claims. In addition, invalid requests have to be rejected as soon as possible by the server in order to keep the resource impact as low as possible and make denial of service attacks much more complex. Consequently, authentication needs to be one of the first steps in the process pipeline of a request. This is the reason why it’s not integral part of the CAP runtime and needs to be configured on application level, for example, by adding additional dependencies. Currently, the CAP Java Runtime supports XSUAA authentication out of the box, but custom authentication can be configured in a flexible manner. Find details about configuring authentication in section Authentication. However, a comprehensive authorization service is fully implemented by the runtime and is available wither by following a declarative approach through the CDS model or by explicitly making usage of the Authorization API. All about authorization is summarized in section Authorization.


As described before, the CAP Java runtime offers out-of-the-box support for the XSUAA authentication service on the SAP Cloud Platform, which is based on OAuth 2.0 protocol. Shortly, the web flow following the OAuth protocol involves three agents:

  • The resource owner (user)
  • The resource server (web service)
  • And the authentication server (XSUAA server).

As first step, the resource owner retrieves a signed access token from the resource server. This token contains all relevant user claims such as user identity, tenant identifier, and granted privileges. Requests to the resource server (web service) bear the token in the authorization header and gets validated before the request is being processed. On successful authentication, the user information is available in the scope of the request.

Spring Boot

To enable authentication with Spring Boot, add the following Maven dependency to the XSUAA library in the pom.xml file of your service:


as well as the dependency to the XSUAA feature:


At runtime, the XSUAA library additionally requires a proper UAA service configuration, which on SAP Cloud Platform Cloud Foundry is accomplished binding a UAA service to your application. Find more details about UAA service configuration on SAP Cloud Platform below.

With the previously mentioned dependencies and a UAA service binding in place, the CAP Java runtime activates a Spring security configuration, which enforces XSUAA authentication for all nonpublic endpoints (according to your CDS model) of CAP services. As a result, these services can’t be invoked without sending a valid token with the user request. There are several application configuration properties to control the default behavior of the security configuration:

  • = false switches off automatic configuration of public CDS service endpoints.
  • = false switches off XSUAA security configuration at all.

The CAP Java Runtime configures authentication for the exposed service endpoints according to the CDS model. Note, that unrestricted service endpoints are accessible for anonymous users!

Maintaining Authentication Manually

If you want to overwrite the automatic security configuration for specific endpoints of your application – for instance if they require an alternative authentication method or should be public – you can add an additional Spring security configuration with a higher priority as done in the following example:

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Order(1) // needs to be evaluated before the standard security configuration
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
      .csrf().disable() // don't insist on csrf tokens in put, post etc.

Here all URLs matching /public/** are opened for public access.

Be cautious with the configuration of the HttpSecurity instance in your custom code. For instance:


will overwrite all endpoints of the application, fully overruling the CAP endpoints in contrast to:


Other frequent examples are Spring actuators that come with own endpoints and that might need custom authentication methods or at least custom authorization. For example, to apply basic authentication to such endpoints, have a look at the following example:

public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {

    public void configure(AuthenticationManagerBuilder auth)
      throws Exception {
      // -> configure basic authentication here with PasswordEncoder etc.

Note, that you have to add the actual configuration of basic authentication.

Plain Java and SAP Java Buildpack

If your application uses plain Java and is deployed as war archive on SAP Cloud Platform with the SAP Java Buildpack, you need to add the Maven dependency to XSUAA in the following way:


Note that the dependency scope is provided here as the SAP Java Buildpack adds the required XSUAA library at deployment time.

Additional configuration is needed to activate XSUAA authentication in the web.xmlfile for the Tomcat server as shown in the following snippet:


See section XSUAA sample application for SAP Java Buildpack for more details.

UI Flows

HTTP endpoints with activated OAuth-based authentication require a bearer token in each request. As explained before, resource owners need to fetch a valid token from the authorization server. For UI-based flows, the token retrieval is typically handled by a UI frontend application, which redirects HTTP requests, that miss an access token, to a dedicated logon page. The frontend can cache the token and append it in subsequent request being forwarded to the backend service.

This approach is shown in the Application Router example for XSUAA.


Authorization is handled by the CAP Java Runtime. By using declarative authorization annotations in your CDS model, the CAP Java Runtime can configure authorization of the affected endpoints automatically. We distinguish between two different authorization methods:

  • Role-based authorization means, that the exposed part of the API depends on the roles, which are assigned to the request user.
  • Instance-based authorization allows to define user privileges even on entity element level, that means a user can only access elements of an entity that fulfill a certain condition.

A precise description of the general authorization concept in CAP can be found in section Authorization.

Role-Based Authorization

You can use the CDS annotation @requires at a CDS service to specify which role a user needs to access the service in general (or, more specifically, to send an event to the service). In addition, use the annotation @restrict on service entity level to specify the role needed to send specific events. Actions and functions can be restricted to certain roles with @requires, respectively.

@restrict and @requires annotations defined on different model levels are evaluated hierarchically (logical AND). For instance, if a user has no access to a service, this also implies that the entities, using actions and functions of the service is forbidden as well. However, several grants in a @restrict annotation of a single entity are logically combined by OR.

The following simple example demonstrates how to model role-based and instance-based authorization. It contains a single DB entity db.books, which is exposed to four different types of users. The access rules for the different users are:

  • Authenticated users can only read columns title, publisher, and price of all books.
  • Users with role vendor have full read access to all books and can also edit books, which have a publisher they’re assigned to.
  • accountant users should be able to read books and trigger accounting action on them.
  • admin users have unrestricted access to all books, but they can’t trigger accounting.
context db {
  entity Books : cuid, managed {
	 title     : localized String(111);
	 publisher : String(111);
	 stock     : Integer;
	 price     : Decimal(9,2);

service CatalogService @(requires: 'authenticated-user') {
  entity Books @(restrict: [{ grant: 'READ' } ])
  as SELECT from db.Books { title, publisher, price };

service EditService @(requires: ['vendor', 'accountant']) {
  entity Books @(restrict: [
    { grant: 'READ' },
    { grant: 'WRITE', to: 'vendor', where: '$user.publishers = publisher' } ])
  as projection on db.Books;

  action doAccounting @(requires:'accountant') ();

service AdminService @(requires: 'admin') {
  entity Books as projection on db.Books;

The table summarizes the privileges of the different users as enforced by the @restrict and @requires annotations in the model:

Role READ WRITE doAccounting
Authenticated user (role not relevant) YES (/browse) NO NO
Vendor YES (/internal or /browse) YES (/internal, but only books with matching published) NO
Accountant YES (/internal or /browse) NO YES (/internal)
Admin YES (/browse or /admin) YES (/admin) NO

Keep in mind that users can have several roles assigned at the same time.

In the current version of CAP Java Runtime, the security annotations are only evaluated on the target entity of the request. Restrictions on second-level entities touched by the query aren’t checked.

This has the following implications:

  • Restrictions of (recursively) expanded or inlined entities of a READ request aren’t regarded.
  • Deep inserts and updates are also only checked on the target entity.

To prevent exposing data of second-level entities through an accessible service entity, minimize the number of exposed associations or compositions in the service entity and add adequate custom handlers to close remaining gaps.

Additional remarks and tips:

  • Don’t forget to restrict auto-exposed entities, which might be open for public access otherwise.
  • WRITE is an accepted abbreviation in the grant clause that comprises all standard CDS events with write semantic: CREATE, UPDATE, UPSERT, and DELETE.

Instance-Based Authorization

Whereas role-based authorization applies to whole entities, only, instance-based authorization allows fine-grained declaration a user is allowed to access within an entity based on his assigned properties. This is also demonstrated in the previous example. vendor users are only allowed to change the entity books, which have a publisher listed in the user’s publisher attribute ($user.publisher). User attributes are presented in the security token sent with the request. Details about the general concept of instance-based authorization can be found in Instance-based access.

Please note, that generally a user attribute referred to with $user.<attribute-name> is interpreted as an array of strings and not single value. (Sub-)Expressions in the where-condition with $user attributes are evaluated element for each user attribute value individually and evaluate to true in case one of the values matches. In the current version, an empty attribute list indicates unrestricted access.

The CAP Java Runtime translates the where-condition in the @restrict annotation to a CQN predicate, which is appended to the CQN statement of the request in an early BEFORE handler. This applies only to READ,UPDATE, and DELETE events.

In the current version of CAP Java Runtime, the following limitations apply:

  • For UPDATE and DELETE events no paths in the where-condition are supported.
  • Paths in where-conditions with to-many associations or compositions aren’t supported.
  • Input data that comes with CREATE, UPDATE or UPSERT isn’t checked against the where-condition. If necessary, custom handlers can cover this in a BEFORE handler.

Authorization and Drafts

The draft flow has some specific implications on the authorization logic that differs from requests to none-draft entities:

  • Draft entities can only be edited by the user who has created it.
  • In general, a grant for a standard CDS event comprises the grants for corresponding draft events. For instance, CREATE implies DRAFT_NEW. Hence, draft events don’t need to be mentioned in @restrict.
  • Instance-based conditions don’t apply for draft entities. But only entities that meet the condition can be activated or put into draft mode.

Create XSUAA Configuration

Compile your CDS model with authentication annotations into a full xs-security.json. For this, run:

mkdir gen
cds compile srv/ --to xsuaa,json > gen/xs-security.json

Note how in xs-security.json the different CDS roles CDS model has been mapped to XSUAA scopes and role template. It’s recommended to add this compile step to your build.

To manually create an XSUAA service with name cds-service-uaa based on this configuration and bind it to the application cds-application, run:

cf create-service xsuaa application cds-service-uaa -c gen/xs-security.json
cf bind-service cds-application cds-service-uaa

Both manual steps aren’t necessary when you model the respective XSUAA service and its dependencies in a deployment manifest before pushing to the cloud.

Set Up the Roles for the Application in the Cloud Cockpit

Once you’ve deployed your application to SAP Cloud Platform, you need set up the roles and role collections in the SAP Cloud Cockpit and assign them to users. This adds the necessary authorization information to the access token when the user logs on to your application through the XSUAA and Application Router.

Following configuration steps need to be done in the SAP Cloud Platform Cockpit within your Subaccount:

  1. Add the roles to role collections

    Navigate to Security > Role Collections. Choose New Role Collection, enter a name, and confirm. Now, click on the new role collection and choose Add Role. Choose the application, role template, and role to finish the creation step.

    In case you added a where clause in the @restrict annotation in the CDS model (which is currently not supported by the runtime), it might be necessary to create a role with corresponding attributes in advance. See section Building Roles and Role Collections for Applications for more details in SAP Cloud Platform documentation.

  2. Assign the role collections to users

    The user role assignment is done in Security > Trust Configuration. Select an IDP and add the assignment to role collection to specific users. See section Assign Role Collections for more details in SAP Cloud Platform documentation..

Mock Users

If security is activated in Spring as described before, the CAP Java Runtime creates a security configuration, which accepts mock users for testing purposes. The mock user configuration only applies if:

  • The service runs without an XSUAA service binding (none-productive mode)
  • Mock users are defined

You can define mock users in a Spring profile, which should be only active during testing as in the following example:

  profiles: testing
        - name: authenticated-user
          password: pass1
        - name: viewer-user
          password: pass2
            - viewer
	  tenant: my-tenant

The first user with name authenticate-user has the ID 0815 and password pass1. No roles are granted. In contrast, user viewer-user has role viewer and tenant ID my-tenant. All users can log in using basic authentication.

In addition, Spring property = false switches off any mock user configuration.

Data Protection and Privacy

Currently, there’s no out-of-the-box support for managing personal data. From the perspective of applications build on CAP, the CAP Java Runtime acts like a container that stores and serves data as defined in the CDS model. Hence, applications need to add required functionality - for example, by means of handlers - to fulfill general requirements with regards to personal data. Data stored by the Persistence Service is protected from unauthorized access - provided adequate access restrictions are declared in the CDS Model as already described.