Alfresco Documentation
Published on Alfresco Documentation (https://docs.alfresco.com)

Home > Alfresco One 5.1.5 > Developer guide > Platform extensions > Tutorials > Web Script Tutorials > Creating a Hello User web script with authentication

Creating a Hello User web script with authentication

To see authentication in action, you can make a slightly more interesting Hello World example named Hello User that requires authenticated access and responds with a personalized greeting.
  1. Log in to Alfresco Share.
    1. Type http://localhost:8080/share in the web browser.
    2. If prompted, log in with the user name admin and password admin.
    3. Click the Repository link in the Share header.
    4. Navigate to Data Dictionary > Web Scripts Extensions.
  2. Create a web script description document for the Hello User example.
    1. In the Create menu, select XML.
    2. Enter hellouser.get.desc.xml as the web script name in the Name field.
    3. Enter the following in the content box:

      
      <webscript>
        <shortname>Hello User</shortname>
        <description>Personalized greeting</description>
        <url>/hellouser</url>
        <authentication>user</authentication>
        <negotiate accept="text/html">html</negotiate>
        <negotiate accept="application/json">json</negotiate>
      </webscript>
      
      
    4. Click Create.
    5. Click the Web Scripts Extensions directory again to return to the folder.
  3. Create a web script response template to render the Hello User greeting.
    1. In the Create menu, select Plain Text.
    2. Enter hellouser.get.html.ftl as the template name in the Name field.
    3. Type Hello ${person.properties.userName} in the content box.
    4. Click Create.
    5. Again, navigate back to the Web Scripts Extensions folder by clicking on it in the breadcrumb trail.
  4. Register the Hello User web script with Alfresco.
    1. Open a new browser tab.
    2. Type http://localhost:8080/alfresco/service/index in the web browser.
    3. If prompted, log in with the user name admin and password admin.
    4. Click Refresh Web Scripts.

      A message indicates there is one additional web script.

  5. Type http://localhost:8080/alfresco/service/hellouser in the web browser to test the new web script.

    A Hello admin message displays indicating your web script is working.

  • Returning a JSON response format [1] While a web script that returns HTML (such as the Hello World sample web script) is fine for rendering a user interface, it is not so good for a data web script that needs to returns a format that is machine-readable, such as JSON. (JSON, short for JavaScript Object Notation, is a lightweight data interchange format, often used for transmitting structured data over a network connection.)
  • Selecting a response format [2] There are several ways for a client to explicitly select a response format: URL extension, URL query parameter, and Accept header.
  • How Hello User works [3] The sample web script required user level authentication in its hellouser.get.desc.xml descriptor file. This indicated to the Web Script Framework that prior to invoking the web script, a user has to first log in.
  • Specifying user identity [4] There are several options for specifying the user with which to invoke a web script: HTTP Basic authentication, Alfresco Ticket, or as a Guest.
  • Using the JSON callback [5] Creating a callback example involves creating an HTML page that invokes the Hello User web script with a callback that displays the JSON response in an alert box.
  • Understanding how the JSON callback works [6] The easiest way to understand the callback example is to invoke the Hello User web script directly and interrogate the response.
Parent topic: Web Script Tutorials [7]

Returning a JSON response format

While a web script that returns HTML (such as the Hello World sample web script) is fine for rendering a user interface, it is not so good for a data web script that needs to returns a format that is machine-readable, such as JSON. (JSON, short for JavaScript Object Notation, is a lightweight data interchange format, often used for transmitting structured data over a network connection.)

A web script can offer multiple response formats where each format is supported by its own response template. Clients that invoke the web script either rely on the default response format or can explicitly ask for a specific response format.

Add another response format to the Hello User web script that returns the greeting in JSON format.

  1. Log in to Alfresco Share.
    1. Type http://localhost:8080/share in the web browser.
    2. If prompted, log in with the user name admin and password admin.
    3. Click the Repository link in the Share header.
    4. Navigate to Data Dictionary > Web Scripts Extensions.
  2. Create a new web script response template to render the Hello User greeting in JSON.
    1. In the Create menu, select Plain Text.
    2. Enter hellouser.get.json.ftl as the template name in the Name field.
    3. Type the following in the Enter Content box.

      {greeting: "hello", user: "${person.properties.userName}"}
    4. Click Create.
    5. Navigate back to the Web Scripts Extensions folder by clicking on it in the bread crumb trail.
  3. Re-register the Hello User web script with Alfresco.
    1. Open a new browser tab.
    2. In the new tab, navigate to http://localhost:8080/alfresco/service/index in the web browser.
    3. If prompted, log in with the user name admin and password admin.
    4. Click Refresh Web Scripts.

    A message indicates there is no additional web script (just a response format has been added).

  4. Finally, type the following on the command line to test the web script.

    curl -uadmin:admin "http://localhost:8080/alfresco/service/hellouser.json"

    The message {greeting: "hello", user: "admin"} displays indicating your web script is working.

Parent topic: Creating a Hello User web script with authentication [8]
Related tasks
Creating a Hello World web script [9]
Creating a Hello User web script [10]

Selecting a response format

There are several ways for a client to explicitly select a response format: URL extension, URL query parameter, and Accept header.
The URL extension approach simply requires the URL to end with the format of the response to select, such as <webscript url>.<format>.

Sometimes, a web script URL cannot support the format extension approach as the URL might naturally end with an extension anyway. For example, web script URL paths that refer to folder and file names in the content repository already have the extension inherited from the file name. For these scenarios, it is possible to explicitly select the response format by using the URL query parameter, such as <webscript url>?format=<format>.

Each format actually maps to a MIME type, which is set on the HTTP response allowing a client to process or render the response appropriately. The Web Script Framework provides a registry of formats where the commonly used MIME types are mapped as follows:

  • html => text/html
  • text => text/plain
  • xml => text/xml
  • atom => application/atom+xml
  • rss => application/rss+xml
  • json => application/json

Another approach to selecting a response format is to use the HTTP Accept header, as defined by RFC 2616 section 14. A client uses an Accept header to specify a prioritized list of preferred MIME types for the response. When the Web Script Framework accepts an HTTP request with an Accept header, it responds with the response format that most closely matches the highest priority preference.

Note: RFC 2616 (http://www.ietf.org/rfc/rfc2616.txt [11]) is the specification for the Hypertext Transfer Protocol – HTTP/1.1.

Web browsers typically provide an Accept header on all their HTTP requests, but most HTTP clients offer some way of specifying an Accept header.

If a client does not explicitly request a specific response format, the web script uses its predefined default response format.

Refer to the following instructions to explicitly select a response format. Each option uses the Hello User sample web script.

  • To use the URL extension approach, type one of the following statements in your command line to explicitly select either HTML or JSON:
    • curl -uadmin:admin "http://localhost:8080/alfresco/service/hellouser.json"
    • curl -uadmin:admin "http://localhost:8080/alfresco/service/hellouser.html"
  • To explicitly select the response format for the Hello User web script using the URL query parameter, type one of the following statements in your command line:
    • curl -uadmin:admin "http://localhost:8080/alfresco/service/hellouser?format=json"
    • curl -uadmin:admin "http://localhost:8080/alfresco/service/hellouser?format=html"
  • To use an Accept header when invoking the Hello User web script to select the response format, type the following in your command line:
    • curl -uadmin:admin -H "Accept: text/html" "http://localhost:8080/alfresco/service/hellouser"
Parent topic: Creating a Hello User web script with authentication [8]
Related tasks
Creating a hello user web script with authentication [10]

How Hello User works

The sample web script required user level authentication in its hellouser.get.desc.xml descriptor file. This indicated to the Web Script Framework that prior to invoking the web script, a user has to first log in.

By default, the Web Script Framework initiates the login process through HTTP Basic authentication, which informs the web browser to display a login box for the user to enter their user name and password. Upon successful authentication, which is performed by the Alfresco content application server, the web script is invoked. Otherwise, the process stops and the invocation of the web script fails.

Having found the hellouser.get.html.ftl response template, the Web Script Framework renders its result back to the web browser. The template, which is now running as an authenticated user, has access to special Alfresco content application server objects. In this case, the template renders the name of the authenticated user through the object ${person.properties.userName}.

Note: HTTP Basic authentication is a method designed to allow a web browser or other client program to provide credentials in the form of a user name and password when making an HTTP request.
Parent topic: Creating a Hello User web script with authentication [8]
Related tasks
Creating a Hello User web script with authentication [8]

Specifying user identity

There are several options for specifying the user with which to invoke a web script: HTTP Basic authentication, Alfresco Ticket, or as a Guest.

HTTP Basic authentication allows you to specify your user name and password within an HTTP request. A request to a web script can include the user name and password of the Alfresco user to authenticate as, meaning the client does not have to ask for them. The cURL client supports this feature.

You can specify an Alfresco Ticket instead of an explicit user name and password. A ticket represents a pre-authenticated user who has already performed the login process. Tickets can be programmatically established by using the pre-built Login web script.

A final option enables you to specify that a web script be executed as an Alfresco guest. Guests are not named users, so do not need to log in; however, they might be restricted in what they can see or do in the Alfresco content repository.

Refer to the following instructions to specify user identity. Each option uses the Hello User sample web script [10].

  • For HTTP Basic authentication, type the following in your command line:

    curl -uadmin:admin "http://localhost:8080/alfresco/service/hellouser"

    This informs cURL to invoke the URL defined by your Hello User web script as the user admin, which returns Hello admin.

    When comparing this to invoking the Hello User web script through the web browser, you can see that the cURL client did not subsequently ask for the user name and password, whereas the web browser did.

    Note: Upon successful authentication, a client might remember that the current session is authenticated, thus requiring the authentication process to be initiated only once. For example, a user already logged in using the current web browser session won't be asked to log in again.
  • To specify an Alfresco Ticket, type the following in your command line to log in:

    curl "http://localhost:8080/alfresco/service/api/login?u=admin&pw=admin"

    This informs cURL to invoke the URL defined by the Login web script, which returns XML similar to the following:

    <?xml version="1.0" encoding="URF-8"?>
    <ticket>TICKET_0a748bc2543f2b271dc4cb9955c11a042cad72cd</ticket>
    1. With a ticket established, it is possible to invoke other web scripts with that ticket, indicating to the Web Script Framework to execute the web script as the user represented by the ticket. This is achieved by adding the following URL query parameter to the web script URL: alf_ticket=<ticket>
    2. To execute the Hello User web script with a ticket, type the following in your command line, substituting the ticket with the value returned from your web script login:

      curl "http://localhost:8080/alfresco/service/hellouser?alf_ticket=TICKET_0a748bc2543f2b271dc4cb9955c11a042cad72cd"
  • For Guest invocation, add the following URL query parameter to the web script URL: guest=true

    Remember, guests can only invoke web scripts that require Guest authentication; they cannot invoke User or Admin required web scripts. To invoke the Hello User web script as guest, type the following in your command line:

    curl "http://localhost:8080/alfresco/service/hellouser?guest=true"

    You might expect this to respond with a polite greeting, but instead you will receive a 401 error message stating that the Hello User web script requires user authentication and a guest has attempted access.

Parent topic: Creating a Hello User web script with authentication [8]
Related tasks
Creating a hello user web script with authentication [10]

Using the JSON callback

Creating a callback example involves creating an HTML page that invokes the Hello User web script with a callback that displays the JSON response in an alert box.
Note: For security reasons, this mechanism is disabled by default. To enable it on any web scripts container, set the bean property: allowCallbacks = true. This change can be made in web-scripts-application-context.xml, or more conveniently outside of the Alfresco WAR file in tomcat/shared/classes/alfresco/extension/custom-web-context.xml.
  1. Create a custom-web-context.xml file in the extension directory (tomcat/shared/classes/alfresco/extension).
  2. Copy the complete bean bean id="webscripts.container from the web-scripts-application-context.xml file located (v5.1) in the ./alfresco/WEB-INF/lib/alfresco-remote-api-5.1.jar/alfresco/web-scripts-application-context.xml into the custom context file.
  3. Add the property <property name="allowCallbacks"> to the bean (see example below):

             
              <bean id="webscripts.container" class="org.alfresco.repo.web.scripts.TenantRepositoryContainer" parent="baseAlfrescoRepositoryContainer" init-method="setup">
                <property name="configService" ref="webscripts.config" />
                <property name="name"><value>Repository</value></property>
                <property name="allowCallbacks"><value>true</value></property>
                <property name="scriptObjects">
                  <map merge="true">
                    <entry key="paging">
                      <ref bean="webscripts.js.paging"/>
                    </entry>
                  </map>
                </property>
                <property name="webScriptsRegistryCache" ref="webScriptsRegistryCache"/>
                <!-- Use the time-limited transaction helper to keep request times to an acceptable duration -->
                <property name="transactionService" ref="transactionService" />
                <!-- The transaction helper used to generate error responses must be unlimited -->
                <property name="fallbackTransactionHelper" ref="retryingTransactionHelper" />
                <property name="authorityService" ref="AuthorityService" />
                <property name="repository" ref="repositoryHelper" />
                <property name="repositoryImageResolver" ref="webscripts.repo.imageresolver" />
                <property name="templateProcessorRegistry" ref="webscripts.repo.registry.templateprocessor" />
                <property name="scriptProcessorRegistry" ref="webscripts.repo.registry.scriptprocessor" />
                <property name="descriptorService" ref="DescriptorService" />
                <property name="tenantAdminService" ref="tenantAdminService" />
                <property name="encryptTempFiles" value="${webscripts.encryptTempFiles}"/>
                <property name="tempDirectoryName" value="${webscripts.tempDirectoryName}"/>
                <property name="memoryThreshold" value="${webscripts.memoryThreshold}"/>
                <property name="maxContentSize" value="${webscripts.setMaxContentSize}"/>
              </bean>
              
     
  4. Restart application server.
  5. Create the HTML page.
    1. Create a file named callback.html on your machine's local file system.
    2. Edit the file and add the following HTML:

        
      <html>
      <body>
      <script>
      // callback function to display greeting
      function showGreeting(res) {alert(res.greeting + ' ' + res.user);}
      // invoke web script hello user web script
      var script = document.createElement('SCRIPT');
      script.type = 'text/javascript';
      script.src = 'http://localhost:8080/alfresco/s/hellouser.json?alf_callback=showGreeting';
      document.body.appendChild(script);
      </script>
      </body>
      </html>
      
      
  6. Test the callback.
    1. Open the file callback.html file in your web browser.
    2. If prompted, log in with the user name admin and password admin.

    An alert box displaying the message hello admin indicates your callback is working.

Parent topic: Creating a Hello User web script with authentication [8]

Understanding how the JSON callback works

The easiest way to understand the callback example is to invoke the Hello User web script directly and interrogate the response.
Type the following in the command line: curl -uadmin:admin "http://localhost:8080/alfresco/s/hellouser.json?alf_callback=showGreeting"

This mimics the web script invocation made in the callback.html file.

The response is:

showGreeting({greeting: "hello", user: "admin"})

This is simply the vanilla Hello User web script response passed as an argument to the function named showGreeting as defined by the alf_callback query parameter. The full response is treated as JavaScript by the web browser, which executes it.

Parent topic: Creating a Hello User web script with authentication [8]

Source URL: https://docs.alfresco.com/5.1/tasks/ws-hello-user-create.html

Links:
[1] https://docs.alfresco.com/../tasks/ws-response-format.html
[2] https://docs.alfresco.com/../tasks/ws-response-format-select.html
[3] https://docs.alfresco.com/../concepts/ws-hello-user-explain.html
[4] https://docs.alfresco.com/../tasks/ws-specify-user-identity.html
[5] https://docs.alfresco.com/../tasks/ws-json-callbacks-using.html
[6] https://docs.alfresco.com/../tasks/ws-json-callbacks-explain.html
[7] https://docs.alfresco.com/../tasks/ws-tutorials.html
[8] https://docs.alfresco.com/../tasks/ws-hello-user-create.html
[9] https://docs.alfresco.com/ws-hello-world-create.html
[10] https://docs.alfresco.com/ws-hello-user-create.html
[11] http://www.ietf.org/rfc/rfc2616.txt