Defining CDS Restrictions and Roles

Objectives
After completing this lesson, you will be able to:

After completing this lesson, you will be able to:

  • Define CDS Restrictions and Roles

Define Restrictions and Roles in CDS: Exercise Overview

Scenario

Before deploying to our productive SAP BTP environment, you want to ensure, that only permitted users can access your app to view and edit data. Therefore, you will first add authorizations to your CAP service and then add two mock users to further test your app locally.

Task Flow

In this exercise, you will perform the following tasks:

  • Implement authentication support - roles and restrictions - for an application.
  • Add local users to test the authentication implementation.

Prerequisites

You have successfully deployed your application manually.

Watching the Simulation and/or Performing the Steps

Note
In this exercise you find a simulation and a list of all steps, displayed in the simulation. Performing the steps below allows you to follow the simulation in your own trial account.

Define Restrictions and Roles in CDS

Business Scenario

Before deploying to our productive SAP BTP environment, you want to ensure, that only permitted users can access your app to view and edit data. Therefore, you will first add authorizations to your CAP service and then add two mock users to further test your app locally.

Task Flow

In this exercise, you will perform the following tasks:

  • Implement authentication support - roles and restrictions - for an application.
  • Add local users to test the authentication implementation.

Prerequisite

You have successfully deployed your application manually.

Prerequisites

Task 1: Enable Authentication Support

To enable authentication support in CAP, a node.js module called passport needs to be installed.

Steps

  1. Enable Authentication Support.

    1. Navigate to your risk-management folder in a terminal in the Business Application Studio. With your cds watch still running in one terminal, it is the easiest to open another second terminal next to it, by invoking Terminal and the New Terminal in the menu. Alternatively, you can also suspend cds watch in your existing terminal by pressing CTRL+C. In both cases, you should already be in the risk-management folder.

    2. Install the passport module. (the --save part makes sure it’s also added as a dependency to your project's package.json)npm install --save passport.

Task 2: Add CAP Role Restrictions to Entities

In this step, you will add authorizations to the Risks service. You will add two different roles RiskManager and RiskViewer with different access scope.

Steps

  1. Add CAP Role Restrictions to Entities.

    1. Open the file srv/risk-service.cds.

    2. Change the code as shown below and add the restrictions (@(...)) to block to your Risks and Mitigations entities. You have to delete code - anything between //### BEGIN OF DELETE and //### END OF DELETE - and add code - anything between //### BEGIN OF INSERT and //### End OF INSERT.

      Code snippet
      using {riskmanagement as rm} from '../db/schema';
      
       /**
         * For serving end users
         */
       service RiskService @(path : 'service/risk') {
       //### BEGIN OF DELETE
         entity Risks as projection on rm.Risks;
       //### END OF DELETE
       //### BEGIN OF INSERT
         entity Risks @(restrict : [
             {
                grant : [ 'READ' ],
                to : [ 'RiskViewer' ]
             },
             {
                 grant : [ '*' ],
                 to : [ 'RiskManager' ]
             }
         ]) as projection on rm.Risks;
       //### END OF INSERT
         annotate Risks with @odata.draft.enabled;
       //### BEGIN OF DELETE
         entity Mitigations as projection on rm.Mitigations;
       //### END OF DELETE
       //### BEGIN OF INSERT
         entity Mitigations @(restrict : [
             {
               grant : [ 'READ' ],
               to : [ 'RiskViewer' ]
             },
             {
               grant : [ '*' ],
               to : [ 'RiskManager' ]
             }
         ]) as projection on rm.Mitigations;
       //### END OF INSERT
           annotate Mitigations with @odata.draft.enabled;
         entity BusinessPartners as projection on rm.BusinessPartners;
       }
      Copy code
    3. Save the file.

Result

With this change, users who are assigned the role RiskViewer can view ("READ") risks and mitigations. Users who are assigned the role RiskManager can view and change risks and mitigations ("*").

Task 3: Add Users for Local Testing

Since the authorization checks have been added to the CAP model, they apply not only when deployed to the cloud but also for local testing. Therefore, you will need a way to log in to the application locally.

CAP allows you to add local users for testing as part of the cds configuration. In this tutorial, we use the .cdsrc.json file to add the users.

The .cdsrc.json file can be used to store project configurations like in the package.json file. Learn more here1.

Steps

  1. Add users for local testing.

    1. In the project, go to the file .cdsrc.json and open it for editing.

    2. In the editor, replace its content with the following lines:

      Code snippet
      
      {
       "[development]": {
         "auth": {
          "passport": {
           "strategy": "mock",
           "users": {
             "risk.viewer@tester.sap.com": {
              "password": "initial",
              "ID": "riskviewer",
              "userAttributes": {
                "email": "risk.viewer@tester.sap.com"
              },
              "roles": ["RiskViewer"]
            },
             "risk.manager@tester.sap.com": {
              "password": "initial",
              "ID": "riskmanager",
              "userAttributes": {
                "email": "risk.manager@tester.sap.com"
              },
              "roles": ["RiskManager"]
            }
           }
          }
         }
        }
       }
      Copy code
    3. Save the file.

      The file defines two users, riskviewer and riskmanager. Let's take a look at the riskmanager example.

      The user is defined by an ID, which can be any identifier for a user. The user has an email, a password parameter, and a rolesparameter.

Task 4: Access the Risk Application with a User and Password

When accessing the Risks or the Mitigations service in the browser, you get a basic authorization pop-up window, asking for your user and password. You can use both users that you defined in the previous step to log in and see how this works.

Steps

  1. Access the Risk Application with a User and Password.

    1. In the tab with the running application, navigate back to the launch page, press refresh in the browser.

    2. Choose the Risks tile and in the app press Go.

    3. In the pop-up, enter the Usernameriskmanager.

    4. Enter the Passwordinitial.

    5. You can now access the Risks application.

Task 5: Caveat

There’s no log out functionality yet. To clear the basic authentication login data from the browser cache, you can either clear the browser cache or simply close all browser windows.

Result

You enabled authentication using passport.js 2. You also added roles and restrictions to control access to your application. Next you will set up SAP Authorization and Trust management.

Reference Links Defining CDS Restrictions and Roles

For your convenience this section contains the external references of this lesson.

If links are used multiple times in a text, only the first location is mentioned in the reference table.

Reference Links: Restrictions and Roles in CDS

Ref#SectionContext text fragmentBrief descriptionLink
1Add Users for Local TestingLearn more here.CAP project configurationhttps://cap.cloud.sap/docs/node.js/cds-env#project-settings
2SummaryYou enabled authentication using passport.jsPassport.jshttp://www.passportjs.org/

Save progress to your learning plan by logging in or creating an account