• Topic
  • Discussion
  • VOS.VAL_AuthenticateVspTutorial(Last) -- DAVWikiAdmin? , 2017-06-29 07:34:58 Edit WebDAV System Administrator 2017-06-29 07:34:58

    VAL VSP Authentication Tutorial

    Introduction

    VAL, the Virtuoso Authentication Layer, provides a means to easily add authentication and ACL support to existing or new VSP-based applications. This tutorial demonstrates the main steps used to do so. We are using curi — the Compressed URI Service — as an example.

    For curi we want to add login information, a means for the user to logout, and ACLs to protect the service.

    Tutorial

    Step 1 - Check for existing authentication information

    The first and simplest step is to check if the user has already provided authentication information as supported by VAL. This can be achieved by simply calling VAL.DBA.authentication_details_for_connection() at the top of the VSP page:


    DECLARE  val_serviceId, 
             val_sid, 
             val_realm, 
             val_uname       VARCHAR ;
    DECLARE  val_isRealUser  INTEGER ;
    
    -- Important since "realm" is an "INOUT" parameter!
    val_realm := NULL;
    
    VAL.DBA.authentication_details_for_connection 
      (
        sid=>val_sid,
        serviceId=>val_serviceId,
        uname=>val_uname,
        isRealUser=>val_isRealUser,
        realm=>val_realm
      );
    

    Note: VAL.DBA.authentication_details_for_connection() will honor a non-NULL realm parameter and only return authentication data for the given realm. Additionally it will honor the app_realm setting in the virtual directory serving the page in question. Thus, there are two ways to define the realm for an application:

    • Set it in the virtual directory
    • Force it manually via the realm parameter

    After the call to VAL.DBA.authentication_details_for_connection(), the application can use the information. The most important one is the value of val_serviceId which defines who is authenticated. If it is NULL, then the user has not authenticated yet.

    Step 2 - Add Log-in and Log-out Links

    VAL provides an authentication (log in) page and a logout page to support the most simple login and logout links possible. Given that the application page is stored in pageUrl, the following links can be used:

    • Authenticate (log in)

      <a href="/val/authenticate.vsp?returnto=<?/pageUrl?>">Login</a>

    • Log out

      <a href="/val/logout.vsp?returnto=<?/pageUrl?>">Logout</a>

      However, in our case a dedicated login page is more desirable, since it allows us to configure certain aspects of authenticate.vsp. Thus, we create a new page login.vsp with the following content (or at least parts of it):

    <?vsp
      connection_set ('__val_auth_page__', '/c/login.vsp');
      connection_set ('__val_req_res_label__', 'Compressed URI Service');
      connection_set ('__val_oauth_scope__', 'basic');
    ?>
    <?include /DAV/VAD/val/authenticate.vsp ?>
    

    The settings should be obvious:

    __val_auth_page__ We tell authenticate.vsp to use login.vsp instead of its own URL for all login links.
    __val_req_res_label__ A custom label for the login dialog to tell the user which service they log into.
    __val_oauth_scope__ The optional OAuth scope to use (basic, profile, or dav). This is only of interest for applications that reuse the created OAuth sessions for additional API calls to the 3rd-party service.

    So we end up with code for creating a login/logout box like the following:


    IF (val_serviceId IS NOT NULL ) 
      {
        http (sprintf ('Logged in as %s', val_serviceId));
        http (sprintf ('<a href="/val/logout.vsp?returnto=%U">Logout</a>', pageUrl));
      }
    ELSE
      {
        http (sprintf ('<a href="login.vsp?returnto=%U">Login</a>', pageUrl));
      }
    

    When the user authenticates, they will be redirected to the pageUrl with a newly created sid cookie. The logout page will remove that cookie.

    Tip: A slightly nicer logged in message with link can be created with code like the following which makes use of the two utility procedures VAL.DBA.get_profile_url() and VAL.DBA.get_profile_name():
    DECLARE  x, n  VARCHAR;
    
    x := VAL.DBA.get_profile_url (val_serviceId);
    
    n := COALESCE (VAL.DBA.get_profile_name (val_serviceId), val_serviceId);
    
    IF (NOT x IS NULL)
      http (sprintf ('<a href="%s">%V</a>', x, n));
    ELSE
      http (n);
    

    Warning: Be aware that WebID logout is not always possible, as it requires a redirect to the unprotected (i.e., HTTP instead of HTTPS) application page.

    Step 3 - Set Up 40x Pages

    A typical situation for authentication-enabled applications is forcing the user to authenticate. Ideally this is done by combining 40x page options in the virtual directory with VAL's authenticate.vsp page (which we used above for the login links). Here, we simply create a new file 40x.vsp which has the following content:


    <?vsp
      connection_set (       '__val_req_res__', 'urn:virtuoso:access:curi'     );
      connection_set ( '__val_req_acl_scope__', 'urn:virtuoso:val:scopes:curi' );
      connection_set ( '__val_req_res_label__', 'Compressed URI Service'       );
      connection_set (     '__val_auth_page__', '/c/login.vsp'                 );
      connection_set (       '__val_err_msg__', http_param ('error.msg')       );
    ?>
    <?include /DAV/VAD/val/authenticate.vsp ?>
    

    authenticate.vsp can be configured via a set of connection settings:

    __val_req_res__ The resource which is protected, i.e., which requires the login. This is only used to retrieve ownership information for the "request access" dialog that authenticate.vsp will show if access was denied. This will default to the returnto URL if not provided, and should that also be NULL (as is the case if authenticate.vsp is used as 40x_page) then the requested URL will be used.
    __val_req_acl_scope__ The ACL scope in which the above resource is protected. This is only used to retrieve ownership information for the "request access" dialog that authenticate.vsp will show if access was denied. If not given, then no "request access" dialog is shown.
    __val_req_res_label__ An optional label for the login dialog showing the user for which service they are authenticating.
    __val_auth_page__ We tell authenticate.vsp to use our custom page login.vsp instead of its own URL for all login links.
    __val_err_msg__ An error message indicating any kind of error. This should be set to http_param ('error.msg') for the simple reason that Virtuoso does clear the http params before processing the 40x page.

    This page will be used as 40x page in the virtual directory configuration:


    DB.DBA.VHOST_DEFINE (
      lpath=>'/c',
      ppath=>'/DAV/VAD/c_uri/',
      is_dav=>1,
      vsp_user=>'CURI',
      ses_vars=>0,
      opts=>vector (
        'url_rewrite', 'c_uri_lst',
        '401_page', '40x.vsp',
        '403_page', '40x.vsp'),
      is_default_host=>0
    );
    

    Then the application can raise a permission denied error as shown in the following example:


    IF (val_serviceId IS NULL) 
      {
        http_status_set(401);
      }
    ELSE
      {
        connection_set ('__val_denied_service_id__', val_serviceId);
        http_status_set(403);
      }
    RETURN '';
    

    If val_serviceId is NULL, then the user has not logged in, and the application simply requests that they do. Otherwise, 403 indicates that permission was denied to the authenticated user. The authenticated user is communicated to authenticate.vsp via the __val_denied_service_id__ connection setting.

    Step 4 - Use ACL Rules to Protect a Web Service

    Above we saw how to use authenticate.vsp as a 40x_page. Now we will add ACL protection to the curi service, and put the new 40x_page to use.

    We want to be able to grant some people the right to create new compressed URIs, and others the right to read these. To that end, we define a new scope, urn:virtuoso:val:scopes:curi, which is only used for curi, and a virtual resource URI which is used to grant permissions, urn:virtuoso:access:curi. These URIs are arbitrary; the scheme we use here is meant to be easily recognizable. In theory they could be any URI one wanted to use.

    VAL makes use of scope definitions to get default access modes for disabled scopes (the default). Thus we start by defining our new scope in the corresponding VAL ACL schema graph (Hint: standard scopes for DAV, etc., are defined in the OpenLink ACL ontology, http://www.openlinksw.com/ontology/acl#; example: oplacl:Dav):


    SPARQL
    PREFIX     acl:  <http://www.w3.org/ns/auth/acl#>
    PREFIX  oplacl:  <http://www.openlinksw.com/ontology/acl#>
    INSERT
      INTO <urn:virtuoso:val:acl:schema> 
        {
          <urn:virtuoso:val:scopes:curi>                           a  oplacl:Scope ;
                                                          rdfs:label  "Compressed URIs" ;
                                                        rdfs:comment  """SQL ACL scope which contains all ACL rules granting permission to 
                                                                         create and read compressed URIs. By default anyone can fully use 
                                                                         the service.""" ;
                                          oplacl:hasApplicableAccess  oplacl:Read   , 
                                                                      oplacl:Write  ;
                                             oplacl:hasDefaultAccess  oplacl:Read   , 
                                                                      oplacl:Write  .
        };
    

    The most important part is oplacl:hasDefaultAccess, which defines the access modes used when ACL evaluation has not been enabled for the curi scope. In such case, everyone is allowed to create and read compressed URIs.

    Now, at the top of the create.vsp page which allows to create new compressed URIs, we add the following ACL check (after the code from above):


    IF (    NOT val_isRealUser 
         OR NOT VAL.DBA.is_admin_user (val_uname)
       ) 
         {
           IF ( NOT VAL.DBA.check_access_mode_for_resource 
                  (
                     serviceId=>val_serviceId,
                     resource=>'urn:virtuoso:access:curi',
                     realm=>val_realm,
                     scope=>'urn:virtuoso:val:scopes:curi',
                     mode=>VAL.DBA.oplacl_iri ('Write'),
                     webidGraph=>val_webidGraph,
                     certificate=>val_cert,
                     honorScopeState=>1
                  )
              ) 
                {
                  connection_set ('__val_denied_service_id__', val_serviceId);
                  connection_set ('__val_req_acl_mode__', VAL.DBA.oplacl_iri ('Write'));
    
                  IF (val_serviceId is NULL)
                    http_status_set(401);
                  ELSE
                    http_status_set(403);
                  RETURN '';
                }
         }
    

    Some of this code we already know from before. But the big first part is new. First we check if we are logged in as an admin user. VAL provides us with the convenient procedure VAL.DBA.is_admin_user() for that. Of course, only "real" (i.e., SQL) users can be administrators of the Virtuoso instance. If no admin credentials were provided, we continue with the ACL check using VAL.DBA.check_access_mode_for_resource(), which allows us to check for exactly one mode on one resource for one service ID. Here we use all the details that were provided by VAL.DBA.authentication_details_for_connection(), and combine them with the resource and scope URIs we defined above.

    Since we want to create a compressed URI, we use the oplacl:Write access mode. Should no ACL exist which grants access, we continue to raise a 40x error. But before we do that, we set two more variables:

    __val_denied_service_id__ This is important, as it allows authenticate.vsp to know that access has been denied to a certain person, and the user should be asked to reauthenticate. Without this setting, having found authentication information, authenticate.vsp would simply return to the returnto URL. This would result in an endless loop. Should no authentication information exist yet, then authenticate.vsp will simply ask for it.
    __val_req_acl_mode__ Like the resource and the scope settings above, the mode is only used for the "request access" dialog. It allows authenticate.vsp to create a more detailed access request message to the resource owner.

    Finally we add the same code to the get.vsp page which handles the conversion of compressed to uncompressed URIs. The only difference is the access mode:


    IF (    NOT val_isRealUser 
         OR NOT VAL.DBA.is_admin_user (val_uname) 
       ) 
         {
           IF ( NOT VAL.DBA.check_access_mode_for_resource 
                  (
                    serviceId=>val_serviceId,
                    resource=>'urn:virtuoso:access:curi',
                    realm=>val_realm,
                    scope=>'urn:virtuoso:val:scopes:curi',
                    mode=>VAL.DBA.oplacl_iri ('Read'),
                    webidGraph=>val_webidGraph,
                    certificate=>val_cert,
                    honorScopeState=>1
                  )
              ) 
                {
                  connection_set ('__val_denied_service_id__', val_serviceId);
                  connection_set ('__val_req_acl_mode__', VAL.DBA.oplacl_iri ('Read'));
                  IF (val_serviceId IS NULL)
                    http_status_set(401);
                  ELSE
                    http_status_set(403);
                  RETURN '';
                }
          }
    

    Step 5 - The Access Request Dialog

    authenticate.vsp provides a simple dialog through which users who have been denied access to a certain resource, may request such access from the resource owner. This dialog is shown by authenticate.vsp if the following conditions hold true:

    If these conditions are fulfilled, the user is given the option to write a message to the owner of the resource, requesting that access be granted.

    Step 6 - Run an Application Under a Specific SQL User Account

    In the case of curi, the VSP pages are not executed as the dba user, but using the dedicated account CURI which improves security and is generally recommended. However, since most of the internal VAL API procedures require special permissions, this user needs to be granted the VAL_AUTH and VAL_ACL roles to be able to execute:


    GRANT VAL_AUTH 
       TO CURI;
    GRANT VAL_ACL 
       TO CURI;
    

    (The API documentation of various procedures includes hints about which role grants the right to execute that procedure.)