CMIS using perl

I’ve had a requirement to get some document details out of Alfresco using perl.

CMIS seems to be the obvious answer and a little bit of googling gives us the WebService::Cmis package.

This seems to do the job nicely but the documentation isn’t great (hint: use the pod) so here is a trival example to recurse through a folder and print out the details of the contents.

#!/usr/bin/perl -w
use Data::Dumper;
use WebService::Cmis;
use Cache::FileCache;

print "Content-type:text/htmlrnrn";

my $client = WebService::Cmis::getClient(
url => "https://myhost/alfresco/cmisatom",
user => '',
password => "",
cache => new Cache::FileCache({
cache_root => "/tmp/cmis_client"
}
)
);

my $repo = $client->getRepository;
# print Dumper($repo);

my $projectFolder = "/Sites/mySite/documentLibrary/myFolder";

my $folder = $repo->getObjectByPath($projectFolder);
# print Dumper($folder);
showFolderContents($folder);

 

 

sub showFolderDetails {
 my $fold = shift;
 print "<h2>".$fold->getTitle()."</h2>n";
# my $props = $fold->getProperties;
#print Dumper($props);
}

sub showDocumentDetails {
 my $doc = shift;
# print Dumper($doc);
 my $props = $doc->getProperties;
 if ($props->{'cmis:isLatestVersion'}->getValue eq 1) {
  #Show mail messages
  if (defined $props->{'imap:messageFrom'}) {
   print $props->{'imap:messageFrom'}->getValue;
   print $props->{'imap:messageTo'}->getValue;
   print $props->{'imap:messageSubject'}->getValue;
   print $props->{'imap:flagAnswered'}->getValue;
  } else {
   print $doc->getTitle()."n";
  }
# print Dumper($props);
 }
}

sub showFolderContents {
 my $fold = shift;

 showFolderDetails($fold);
 my $projects = $fold->getChildren();
 while (($entry = $projects->getNext())){

   if ($entry->isa("WebService::Cmis::Folder")) {
      showFolderContents($entry);
   } else {
      showDocumentDetails($entry);
   }
 }
}

 

Alfresco CMIS host name

The problem we’ve been having is to do with our Alfresco server name when using CMIS.

We are running our Alfresco instance behind an Apache server (on a different box) and the default configuration means that when we make a call to the CMIS server all the links returned have the link to the Alfresco host which we can’t follow as it’s behind a firewall.

ApacheHost.org -> AlfrescoHost.org

e.g.  Make a call to https://ApacheHost.org/alfresco/service/cmis and all the links come back with AlfrescoHost.org as part of the URL

The solution described here Alfresco JIRA issue is as follows:

Add to the file

tomcat/shared/classes/META-INF/spring-webscripts-config-custom.xml

(You may need to create the file)

 <alfresco-config>

    <config evaluator="string-compare" condition="Server">
       <server>
          <scheme>http</scheme>
          <hostname>your-public-host</hostname>
          <port>your-port</port>
          <path>alfresco</path>
       </server>
    </config>

 </alfresco-config>

 

If you haven’t done it already then it’s probably worth adding/changing the following in alfresco-global.properties as well

alfresco.context=alfresco
alfresco.host=${localname}
alfresco.port=8080
alfresco.protocol=http

share.context=share
share.host=${localname}
share.port=8080
share.protocol=http

XForms(Orbeon), REST, CMIS and Alfresco – part 2 Files

To keep things simple this example uses basic authentication – to see how to handle authentication in more detail see part 1 here

This is a relatively straightforward example of how to upload a file into Alfresco from Orbeon using CMIS over REST.

I’m not going to cover the details of how the REST interface works (as usual POST for create, PUT for update) or go into depth about how to use CMIS as this is covered elsewhere e.g. ECM Architect article on CMIS

Starting from the standard example of how to upload a file in Orbeon the changes to make are:

  • Instead of posting a multi-part mime message by using the method form-data-post use a normal post and encode the file using xxforms:doc-base64
  • Use the test: (echo: in 3.9) action – after this has been done the file will be uploaded to the server in a temporary directory
  • Create a second submission to post the file to Alfresco

An alternative way to encode the file would be to use the technique described here with a serialized element replacing the media element. This is simpler but less instructive.

For the second submission I use a template file containing a blank CMIS entry and fill in the appropriate fields, you can populate any aspect data fields here. I’ve either used xforms:setvalue or xslt as part of an xpl pipeline depending on what I’m doing – here I’m keeping it simple and just using setvalue.

The contents of the xforms:dispatch element are used to control the parameters to set as part of the upload submission (you’ll see that the file is sent to a test directory in this example) – there are a very limited set of parameters here but it’s easy enough to add more.

(I haven’t done any error handling although you can see what to do using the ins-cmis-rest-control instance)

Gotchas

  • According to the atom spec the contents of the atom:content are treated differently according to the value of the type attribute – it’s therefore safer to use cmisra:content instead
  • If there’s an error in Alfresco, e.g. trying to create two files with the same name, then Alfresco will return text/html not text/xml even if you ask it nicely.

It’s worth noting that if you try and POST the same file twice you will get a 500 response – if you try and upload the same file twice via Share then you get a second file with the suffix (1)

This covers the basics of how to upload a file from Orbeon to Alfresco using the CMIS REST interface.

Updating a file, using PUT or deleting are fairly straightforward after this. (Note that the metadata and file contents are different things so are updated separately.)

Enough talking – here’s the example

 <html xmlns:xforms="http://www.w3.org/2002/xforms"
    xmlns:f="http://orbeon.org/oxf/xml/formatting"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:xxforms="http://orbeon.org/oxf/xml/xforms"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xxi="http://orbeon.org/oxf/xml/xinclude"
    xmlns:ev="http://www.w3.org/2001/xml-events"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:fr="http://orbeon.org/oxf/xml/form-runner"
    xmlns:xi="http://www.w3.org/2001/XInclude"
      xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/"
    xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/"
    xmlns:alf="http://www.alfresco.org">

<head>

<title>Spike Upload</title>

<xforms:model id="cmis-rest-model">
    <xxforms:variable name="alfresco-uri"
        select="xxforms:property('alfresco.uri')"
        as="xs:anyURI" />
    <xxforms:variable name="alfresco-username"
        select="xxforms:property('alfresco.username')"
        as="xs:string" />
    <xxforms:variable name="alfresco-credentials"
        select="xxforms:property('alfresco.credentials')"
        as="xs:string" />
    <xforms:instance id="ins-cmis-rest-control">
        <control>
            <status />
        </control>
    </xforms:instance>

    <xforms:instance id="ins-cmis-rest-create-file">
        <xi:include href="create-file.xml" xxi:omit-xml-base="true" />
    </xforms:instance>
    <xforms:instance id="ins-cmis-rest-create-file-result">
        <atom:entry />
    </xforms:instance>
    <xforms:instance id="ins-upload">
        <upload xmlns="">
            <summary />
            <media filename="" mediatype="" size=""
                                            xsi:type="xs:anyURI" />
            <category>term="foo"; scheme="bar"; label="baz"</category>
        </upload>
    </xforms:instance>

    <xforms:instance id="ins-upload-template">
        <upload xmlns="">
            <summary />
            <media filename="" mediatype="" size=""
                                            xsi:type="xs:anyURI" />
            <category>term="foo"; scheme="bar"; label="baz"</category>
        </upload>
    </xforms:instance>

    <xforms:submission id="sub-background-upload"
        ref="instance('ins-upload')" method="post" replace="none"
        resource="test:" validate="false" />

    <xforms:submission
                id="sub-form-data-post"
                method="post"
                action="test:"
                ref="instance('ins-upload')"
                replace="instance"
                instance="ins-post-response">

        <xforms:header>
            <xforms:name>Accept</xforms:name>
            <xforms:value>application/atom+xml</xforms:value>
        </xforms:header>

        <xforms:action ev:event="xforms-submit-done">
            <xxforms:variable name="media-entry"
                                   select="instance('ins-upload')"/>
            <xxforms:variable name="file-uri"
                             select="instance('ins-upload')/media"/>

            <xforms:dispatch target="cmis-rest-model"
                                       name="cmis-rest-upload-file">
                <xxforms:context name="fr:media-entry"
                                             select="$media-entry"/>
                <xxforms:context name="fr:media-title"
                            select="$media-entry//media/@filename"/>
                <xxforms:context name="fr:media-type"
                         select="$media-entry//atom:content/@type"/>

                <xxforms:context name="fr:file-content"    
                          select="xxforms:doc-base64($file-uri)" />

            </xforms:dispatch>
            <xforms:insert nodeset="instance('ins-upload')"
                         origin="instance('ins-upload-template')" />
            <xforms:send submission="sub-get-feed" />
        </xforms:action>
    </xforms:submission>

    <xforms:instance id="ins-post-response">
        <foo xmlns="" />
    </xforms:instance>

    <xforms:submission id="sub-get-feed" method="get"
        instance="ins-feed" serialization="none"
        resource="{$alfresco-uri}service/cmis/p/test/children"
        mediatype="application/atom+xml"
        xxforms:username="{$alfresco-username}"
        xxforms:password="{$alfresco-credentials}" replace="instance">
    </xforms:submission>

    <xforms:instance id="ins-feed">
        <atom:feed />
    </xforms:instance>

    <xforms:send ev:event="xforms-model-construct-done"
        submission="sub-get-feed" />

    <xforms:action ev:event="cmis-rest-upload-file">
        <xxforms:variable name="media-type"
                                   select="event('fr:media-type')"/>
        <xxforms:variable name="content"
                                 select="event('fr:file-content')"/>
        <xforms:delete
            nodeset="instance('ins-cmis-rest-create-file')/atom:entry/*" />
        <xforms:insert
            context="instance('ins-cmis-rest-create-file')/atom:entry"
            origin="instance('ins-cmis-rest-create-file-template')/atom:entry/*"
            at="last()" position="after" />

        <xforms:setvalue
            ref="instance('ins-cmis-rest-create-file')//atom:title"
            value="event('fr:media-title')" />

        <xforms:setvalue
            ref="instance('ins-cmis-rest-create-file')
                                     //cmisra:content/cmisra:base64"
            value="$content" />

        <xforms:setvalue
            ref="instance('ins-cmis-rest-create-file')
                                  //cmisra:content/cmisra:mediatype"
            value="$media-type" />

        <xforms:setvalue
            ref="instance('ins-cmis-rest-create-file')
//cmis:propertyString
    [@propertyDefinitionId='cmis:contentStreamMimeType']/cmis:value"
            value="$media-type" />

        <!-- You can set any values you like here
               e.g. a custom document type or aspect properties -->
        <xforms:send submission="cmis-rest-create-file-submission" />

    </xforms:action>
    <xforms:submission ref="instance('ins-cmis-rest-create-file')"
        id="cmis-rest-create-file-submission" method="post"
        action="{$alfresco-uri}service/cmis/p/test/children"
        mediatype="application/atom+xml"
        xxforms:username="{$alfresco-username}"
        xxforms:password="{$alfresco-credentials}" replace="instance"
        instance="ins-cmis-rest-create-file-result">
        <!-- This doesn't actually help for errors,
                    e.g. 2 files with the same name, as Alfresco
              always returns a 500 with Content-Type: text/html  -->
        <xforms:header>
            <xforms:name>Accept</xforms:name>
            <xforms:value>text/xml</xforms:value>
        </xforms:header>
        <xforms:action ev:event="xforms-submit-error">
            <xforms:setvalue
                ref="instance('ins-cmis-rest-control')//status"
                value="'fail'" />
            <xforms:message level="modal"
                value="concat('An error occurred while creating
                 a file in Alfresco. Please inform an administrator.
                         (error-type:',event('error-type'), ')')" />
        </xforms:action>
        <xforms:action ev:event="xforms-submit-done">
    <xforms:setvalue ref="instance('ins-cmis-rest-control')//status"
                value="'ok'" />
        </xforms:action>
    </xforms:submission>
</xforms:model>

</head>
<body>

    <h1>Spike Upload</h1>

    <xforms:group ref="instance('ins-upload')">

        <p>

            <!-- Upload field -->
            <xforms:upload ref="media" xxforms:size="60">
                <xforms:label>Upload file: </xforms:label>
                <xforms:filename ref="@filename" />
                <xforms:mediatype ref="@mediatype" />
                <xxforms:size ref="@size" />
            </xforms:upload>

            <xforms:output value="media" appearance="xxforms:download">
                <xforms:label>Download</xforms:label>
                <xforms:filename ref="@filename" />
                <xforms:mediatype ref="@mediatype" />
            </xforms:output>

        </p>

        <p>
            <xforms:textarea ref="summary">
                <xforms:label>Summary: </xforms:label>
            </xforms:textarea>
        </p>

    </xforms:group>

    <p>
        <xforms:submit submission="sub-form-data-post">
            <xforms:label>Submit (form-data-post)</xforms:label>
        </xforms:submit>
    </p>

    <hr />

    <fr:datatable paginated="false">
        <thead>
            <tr>
                <th fr:sortable="true" fr:resizeable="true">File Name</th>
                <th fr:sortable="true" fr:resizeable="true">Published</th>
                <th fr:sortable="true" fr:resizeable="true">Author</th>
                <th>Summary</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <xforms:repeat id="rep-media"
                nodeset="instance('ins-feed')/atom:entry">
                <tr>
                    <td><xforms:output ref="atom:title" /></td>
                    <td><xforms:output ref="atom:published"
                            xxforms:format="format-dateTime(., '[Y0001]-[M01]-[D01]')" /></td>
                    <td><xforms:output ref="atom:author/atom:email" /></td>
                    <td><xforms:output ref="atom:summary" /></td>
                    <td></td>
                </tr>
            </xforms:repeat>
        </tbody>
    </fr:datatable>

</body>
</html>

The template file:

 <?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
    xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/"
    xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/"
    xmlns:alf="http://www.alfresco.org">
    <title>sample-a.doc</title>
    <summary>A sample whitepaper named Sample A</summary>
    <cmisra:content>
        <cmisra:mediatype></cmisra:mediatype>
        <cmisra:base64></cmisra:base64>
    </cmisra:content>
    <cmisra:object>
        <cmis:properties>
            <cmis:propertyId
                propertyDefinitionId="cmis:objectTypeId">
                         <cmis:value>cmis:document</cmis:value>
            </cmis:propertyId>
            <cmis:propertyString
                propertyDefinitionId="cmis:contentStreamMimeType">
                     <cmis:value>text/xml</cmis:value>
            </cmis:propertyString>
            <alf:setAspects>
                <alf:appliedAspects>P:cm:titled</alf:appliedAspects>
                <alf:appliedAspects>P:rn:renditioned</alf:appliedAspects>
                <alf:appliedAspects>P:cm:taggable</alf:appliedAspects>
                <alf:appliedAspects>P:cm:templatable</alf:appliedAspects>
                <alf:appliedAspects>P:cm:author</alf:appliedAspects>
                <alf:appliedAspects>P:app:inlineeditable</alf:appliedAspects>
                <alf:properties>
                    <cmis:propertyString
                            propertyDefinitionId="cm:author"
                            displayName="Author"
                            queryName="cm:author">
                           <cmis:value></cmis:value>
                     </cmis:propertyString>
                    <cmis:propertyString
                            propertyDefinitionId="cm:title"
                            displayName="Title"
                            queryName="cm:title">
                           <cmis:value></cmis:value>
                    </cmis:propertyString>
                </alf:properties>
            </alf:setAspects>
        </cmis:properties>
    </cmisra:object>
</entry>

 

XForms (Orbeon), CAS and CMIS (Alfresco) – Part 1 – Authentication

I thought I’d write about my experience of using the Alfresco CMIS interface as a backend to a custom XForms application.
There’s a natural fit here as the atom based syntax of CMIS fits very nicely with XForms however there are a few little wrinkles to work through.

Authentication

The first issue to decide on is how to handle the authentication of the CMIS service – this will very much depend on your application requirements and architecture. As you will see from earlier posts we are running behind CAS with both our Alfresco and Orbeon apps using CAS authentication (Orbeon via Spring Security).

Due to the application requirements I am using two different authentication strategies – a well known generic user and proxy authentication using the logged in user.

Basic Auth

This is the easiest to set up and use

The way I’ve done this is to define some configuration properties to set the user name etc and assign these to variables within the model

 

<xxforms:variable name="alfresco-uri"
     select="xxforms:property('chassis.alfresco.uri')"
     as="xs:anyURI"/>
<xxforms:variable name="alfresco-username"
     select="xxforms:property('chassis.alfresco.username')"
     as="xs:string"/>
<xxforms:variable name="alfresco-credentials"
     select="xxforms:property('chassis.alfresco.credentials')"
     as="xs:string"/>
<xxforms:variable name="is-send-alfresco"
     select="xxforms:property('chassis.alfresco.send')"
     as="xs:boolean"/>

Retrieving information is then via a straightforward submission using xxforms:username and xxforms:password (obviously you need to set the path of the action appropriately)

<xforms:submission id="cmis-rest-get-file-record" method="get"
  action="{$alfresco-uri}service/cmis/p/User Homes/TestUser/children"
  mediatype="application/atom+xml"
  xxforms:username="{$alfresco-username}"
  xxforms:password="{$alfresco-credentials}"
  replace="instance"
  instance="ins-cmis-rest-create-file"
  if="$is-send-alfresco"
  serialization="none"/>

This uses basic auth which will work with an out of box Alfresco but does have the limitations of basic auth i.e. it’s not very secure unless you use https

Proxy Auth

First thing to note in following on is that this has to be done using https as otherwise CAS won’t like it.

The complication here is that the requests to the Alfresco server are being sent from Orbeon not directly from the user so although the user is logged into both Orbeon and Alfresco the CMIS requests will not be authenticated.

The way I’ve chosen to do this is to implement a servlet filter to obtain an Alfresco authentication ticket which can then be passed through to Orbeon as part of the request and appended to the CMIS request.

You will see here that the code uses HttpClient 3.1 (because I’m still using Orbeon 3.8) but it should be fairly trivial to upgrade.

I also use JNDI to retrieve the name of the Alfresco service e.g. <Environment name=”alfrescoApp” type=”java.lang.String” value=”https://alfresco/alfresco”/> – you may want to do this differently.

package org.aelfric.demo.security;

import java.io.IOException;

import javax.naming.NamingException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author iwright
 *
 */
public class AlfrescoCASFilter implements Filter {

  private Log log = LogFactory.getLog(this.getClass());

  public static final String ALFRESCO_TICKET = "alf_ticket";

  public void doFilter(ServletRequest request,
                          ServletResponse response,
                          FilterChain chain)
                       throws IOException, ServletException {
    if (request instanceof HttpServletRequest &&
                        response instanceof HttpServletResponse) {
      doHttpFilter((HttpServletRequest)request,
                        (HttpServletResponse)response, chain);
    } else {
      throw
        new ServletException("only HTTP request and responses are
                                         supported by this filter");
    }
  }

  @Override
  public void doHttpFilter(HttpServletRequest request,
    	           HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
    log.debug("request inbound");

    HttpClient client = new HttpClient();
    String ticket = null;
    try {
	ticket = AlfrescoCASFilter.getAlfrescoTicket(request, client);
    } catch (NamingException e) {
	log.error("Need to set JNDI variable alfrescoApp if using Alfresco", e);
    }
    if (ticket != null) {
	request.setAttribute(ALFRESCO_TICKET, ticket);
    }
    log.debug("alfresco ticket:" + ticket);
    chain.doFilter(request, response);

    log.debug("response outbound");
  }

  public static String getAlfrescoTicket(HttpServletRequest req,
                                                 HttpClient client)
            throws UnsupportedEncodingException, IOException, HttpException,
            ServletException, NamingException {

    HttpSession httpSess = req.getSession(true);

    // Get CAS information
    Assertion assertion = (Assertion) httpSess
                .getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
    if (assertion == null) {
       return "";
    }
    String username = assertion.getPrincipal().getName();
        // Read out the ticket id
    String ticket = null;
    String alfrescoWebAppURL = LookupJNDI.<String> getEnvEntry(ALFRESCO_WEBAPP_URL_CONFIG);
    if (alfrescoWebAppURL == null) {
       return (null);
    }
    String proxyticket = assertion.getPrincipal().getProxyTicketFor(
                alfrescoWebAppURL);

    if (proxyticket == null) {
      return (null);
    }
    String casLoginUrl = alfrescoWebAppURL + "/service/api/logincas?u="
                + URLEncoder.encode(username, "UTF-8") + "&t="
                + URLEncoder.encode(proxyticket, "UTF-8");

    GetMethod method = new GetMethod(casLoginUrl);
    method.setRequestHeader("cookie", req.getHeader("cookie"));
    int statusCode = client.executeMethod(method);
    // Read back the ticket
    if (statusCode == 200) {
      InputStream is = method.getResponseBodyAsStream();
      // do something with the input stream
      BufferedReader in = new BufferedReader(new InputStreamReader(is));
      String line;
      String responseText = "";
      while ((line = in.readLine()) != null) {
        responseText += line;
      }
      in.close();
      ticket = responseText;

   } else {
      if (log.isDebugEnabled()) {
        log.debug("Authentication failed, received response code: "
                        + statusCode);
      }
   }
   method.releaseConnection();
   return ticket;
  }
}

The next step is to configure the servlet filter in your web.xml for any URLs where you want to proxy authenticate.

 <filter-mapping>
        <filter-name>AlfrescoCASFilter</filter-name>
        <url-pattern>/study/*</url-pattern>
    </filter-mapping>

Once you’ve done this then the request will contain an attribute with the Alfresco ticket.

Now for the Orbeon part.

For information I hold cmis-rest as a separate model but I’m trying to simplify the examples by leaving that out.

When the model is contructed the requested attribute is held in a control instance.

<xforms:instance id="ins-cmis-rest-control">
        <control>
            <ticketAuth/>
        </control>
</xforms:instance>

<xforms:instance id="ins-cmis-rest">
        <request/>
</xforms:instance>

<!-- Note that this has to be done as part of the
                              xforms-model-construct-done stage -->
<xforms:action ev:event="cmis-rest-get-ticket">
   <xforms:insert
      nodeset="instance('ins-cmis-rest')"
      origin="xxforms:get-request-attribute('alf_ticket')"/>
   <xforms:setvalue ref="instance('ins-cmis-rest-control')//ticketAuth"
                value="instance('ins-cmis-rest')"/>
</xforms:action>

<xforms:action ev:event="xforms-model-construct-done">
      <xforms:dispatch name="cmis-rest-get-ticket"/>
</xforms:action>

So now when the submission is sent the Alfresco ticket can be appended to the URL

So the equivalent submission but with proxy authentication is:

 <xforms:submission id="cmis-rest-get-file-record" method="get"
       action="
{$alfresco-uri}service/cmis/p/User Homes/
           TestUser/children?alf_ticket={instance('ins-cmis-rest')}"
mediatype="application/atom+xml" replace="instance"
instance="ins-cmis-rest-create-file" serialization="none"/>

Share CAS logout

Update – since surf 1.2 (at least) the Surf LogoutController understands the redirectURL request parameter (and redirectURLQueryKey, redirectURLQueryValue) which makes this all unnecessary – add the parameters to the end of the dologout call in the header – how depends on the version of Share – in share-config-custom.xml for the old style header – see  here for the new style header

I’ve finally had the time to work out how to configure Alfresco Share to successfully log out when using CAS to log in.

If you log out of just CAS you will still be logged into Share and vice versa so you need to log out of both – and just for good measure log out of Alfresco at the same time.

This follows on from Martin Bergljung’s blog on configuring for CAS

(Note this doesn’t do anything about single sign out as that’s a different problem)

The way I’ve done this is to override the logoutController by defined a new java class and referencing it in custom-slingshot-application-context.xml

 <!-- Override Logout Controller - to expire Alfresco tickets -->
   <bean id="logoutController" class="org.wrighting.web.site.servlet.CASSlingshotLogoutController">
      <property name="cacheSeconds" value="-1" />
      <property name="useExpiresHeader"><value>true</value></property>
      <property name="useCacheControlHeader"><value>true</value></property>
      <property name="connectorService" ref="connector.service" />
      <!-- if blank assumes the same as Share -->

      <property name="casHost"><value>https://alfresco</value></property>
      <property name="casPath"><value>sso/logout</value></property>

   </bean>

You’ll see here that I’ve defined a couple to properties to indicate where the CAS log out page lies – this is where the user will be redirected when they log out. This fits quite closely with the method of configuring the CAS server in the web.xml but you could use an alternative approach such as properties.

The java code is very closely based on org.alfresco.web.site.servlet.SlingshotLogoutController however there is one significant difference in that it doesn’t call handleRequestInternal in LogoutController.
This is because LogoutController.handleRequestInternal ends up redirecting to request.getContextPath whereas we want to go to our CAS logout page however it’s still necessary to make sure that you call AuthenticationUtil.logout which would normally be done in the LogoutController.

package org.wrighting.web.site.servlet;

import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.surf.UserFactory;
import org.springframework.extensions.surf.mvc.LogoutController;
import org.springframework.extensions.surf.site.AuthenticationUtil;
import org.springframework.extensions.surf.support.AlfrescoUserFactory;
import org.springframework.extensions.webscripts.connector.AlfrescoAuthenticator;
import org.springframework.extensions.webscripts.connector.Connector;
import org.springframework.extensions.webscripts.connector.ConnectorContext;
import org.springframework.extensions.webscripts.connector.ConnectorService;
import org.springframework.extensions.webscripts.connector.HttpMethod;
import org.springframework.extensions.webscripts.connector.Response;
import org.springframework.web.servlet.ModelAndView;

/**
 * CAS specific override of the Share specific override of the SpringSurf
 * dologout controller.
 * <p>
 * The implementation ensures Alfresco tickets are removed if appropriate and as
 * it can't delegates to the SpringSurf implementation for framework cleanup
 * does that clean up and then sends a logout to the CAS host
 *
 * @see org.alfresco.web.site.servlet.SlingshotLogoutController
 *
 * @author Ian Wright
 */
public class CASSlingshotLogoutController extends LogoutController {
    private static Log logger = LogFactory
            .getLog(CASSlingshotLogoutController.class);
    private ConnectorService connectorService;
    private String casHost;
    private String casPath;

    /**
     * @param connectorService
     *            the ConnectorService to set
     */
    public void setConnectorService(ConnectorService connectorService) {
        this.connectorService = connectorService;
    }

    @Override
    public ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        try {
            HttpSession session = request.getSession(false);
            if (session != null) {
                // retrieve the current user ID from the session
                String userId = (String) session
                        .getAttribute(UserFactory.SESSION_ATTRIBUTE_KEY_USER_ID);

                if (userId != null) {
                    // get the ticket from the Alfresco connector
                    Connector connector = connectorService.getConnector(
                            AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID, userId,
                            session);
                    String ticket = connector.getConnectorSession()
                            .getParameter(
                                    AlfrescoAuthenticator.CS_PARAM_ALF_TICKET);

                    if (ticket != null) {
                        // if we found a ticket, then expire it via REST API -
                        // not all auth will have a ticket i.e. SSO
                        Response res = connector.call("/api/login/ticket/"
                                + ticket, new ConnectorContext(
                                HttpMethod.DELETE));
                        if (logger.isDebugEnabled())
                            logger.debug("Expired ticket: " + ticket
                                    + " user: " + userId + " - status: "
                                    + res.getStatus().getCode());
                    }
                }
            }
        } finally {
            AuthenticationUtil.logout(request, response);
            String target = request.getContextPath();
            if (casHost != null && casHost.length() > 0) {
                target = casHost;
            } else {
                URL reconstructedURL = new URL(request.getScheme(),
                        request.getServerName(),
                        request.getServerPort(),
                        "");
                target = reconstructedURL.toExternalForm();
            }
            if (casPath != null && casPath.length() > 0) {
                target += '/' + casPath;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Logout to:" + target);
            }
            response.sendRedirect(target);
        }

        return null;
    }

    /**
     * @param casHostValue
     *            the casHost to set - defaults to the same as Share
     */
    public void setCasHost(String casHostValue) {
        casHost = casHostValue;
    }

    /**
     * @param casPathValue
     *            the location of the CAS logout servlet
     */
    public void setCasPath(String casPathValue) {
        casPath = casPathValue;
    }
}

 

Alfresco debugger in a VirtualBox VM

How to run the Alfresco Server Side debugger when running in an Ubuntu Virtual Box VM

Edit /opt/alfresco-3.4.d/tomcat/scripts/ctl.sh to add:
DISPLAY=:0.0
export DISPLAY

The other trick is to make sure that you type ‘xhost +’

You will need to do this in a shell window AND in the shell from which you restart alfresco

The Web Script /alfresco/service/api/javascript/debugger has responded with a status of 500 – Internal Error.

500 Description: An error inside the HTTP server which prevented it from fulfilling the request.

Message: 08090007 Wrapped Exception (with status template): Could not initialize class sun.awt.X11GraphicsEnvironment

Exception: java.lang.NoClassDefFoundError – Could not initialize class sun.awt.X11GraphicsEnvironment

CAS, Alfresco and WebDAV

Having successfully configured Alfresco (and Share) to authenticate using CAS – it’s documented here

The next challenge is to try and work out how to get this authentication working with webdav
Update:

One way to do this this is to bypass CAS and authenticate against the underlying CAS datastore directly by adding a new authentication component.

Of course this means that you are not using CAS but then as you are likely to be accessing WebDAV outside of the browser the single sign on capabilities are not particularly relevant

We use Drupal as our underlying CAS data store so there’s a bit of custom code here – you may be able to just configure the authentication chain if you’re using a different method e.g. LDAP

So in alfresco-global.properties add to the authentication chain:
authentication.chain=cas:external,localDrupal:drupal

While you’re there set up some database connection properties e.g.

drupal.db.driver=org.gjt.mm.mysql.Driver
drupal.db.username=drupal
drupal.db.password=drupal
drupal.db.url=jdbc:mysql://localhost:3306/drupal6

I’m not going to cover ensuring that you have access to the mysql database here. If it’s on a different machine you’ll need to configure MySQL as well as any firewall rules.

Next it’s time to tell Alfresco about the new component that you are creating so create the directory alfresco/subsystems/Authentication/drupal and add the following files:

drupal-authentication-context.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://www.springframework.org/schema/beans" 
xsi:schemalocation="http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean class="org.apache.commons.dbcp.BasicDataSource" 
                       destroy-method="close" id="drupalDataSource">
       <property name="driverClassName" value="${drupal.db.driver}"/>
        <property name="url" value="${drupal.db.url}"/>
        <property name="username" value="${drupal.db.username}"/>
        <property name="password" value="${drupal.db.password}"/>
        <property name="validationQuery" value="SELECT 1"/>
        <property name="testOnBorrow" value="true"/>
        <property name="defaultAutoCommit" value="false"/>
        <property name="maxWait" value="5000"/>
    </bean>

    <bean class="mypackage.authentication.DrupalAuthenticationComponentImpl" 
id="drupalAuthenticationComponent" parent="authenticationComponentBase"> 
<property name="dataSource" ref="drupalDataSource"/>
        <property name="nodeService">
            <ref bean="nodeService"/>
        </property>
        <property name="personService">
            <ref bean="personService"/>
        </property>
        <property name="transactionService">
            <ref bean="transactionService"/>
        </property>
</bean>

      <!-- Wrapped Drupal authentication component to be used within subsystem -->
    <bean id="AuthenticationComponent">
        <property name="proxyInterfaces">
            <value>org.alfresco.repo.security.authentication.AuthenticationComponent</value>
        </property>
        <property name="transactionManager">
            <ref bean="transactionManager"/>
        </property>
        <property name="target">
            <ref bean="drupalAuthenticationComponent"/>
        </property>
        <property name="transactionAttributes">
            <props>
                <prop key="*">${server.transaction.mode.default}</prop>
            </props>
        </property>
    </bean>
     <!-- Authentication service for authentication component chaining

     Note. the id of this bean must be 'localAuthenticationService' for it to
     be picked up, as an authentication service, by the
     Subsystem Chaining Authentication Service
    -->
    <bean id="localAuthenticationService">
        <property name="ticketComponent">
            <ref bean="ticketComponent"/>
        </property>
        <property name="authenticationComponent">
            <ref bean="drupalAuthenticationComponent"/>
        </property>
        <property name="sysAdminParams">
            <ref bean="sysAdminParams"/>
        </property>
    </bean>
</beans>

 

drupal-authentication.properties

drupal.db.driver=org.gjt.mm.mysql.Driver
drupal.db.username=drupal
drupal.db.password=drupal
drupal.db.url=jdbc:mysql://localhost:3306/drupal6

 

Then create the bean that is referenced from the config

package mypackage.cms.authentication;

import org.alfresco.repo.management.subsystems.ActivateableBean;
import org.alfresco.repo.security.authentication.AbstractAuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.security.MessageDigest;

/**
 * Authenticates a user by Drupal.
 * <p/>
 * The authentication is done against the database table USERS and the
 * column NAME (username) and column PASS (MD5 password)
 * <p/>
 * Tested with Drupal 6
 *
 * @author martin.bergljung@ixxus.co.uk
 */
public class DrupalAuthenticationComponentImpl 
extends AbstractAuthenticationComponent implements ActivateableBean {
    public static final String GET_USER_PWD_SQL = "SELECT pass FROM users WHERE name=?";

    private final Log logger = LogFactory.getLog(getClass());

    /**
     * Spring JDBC template used to query or update a JDBC data source
     */
    private JdbcTemplate m_jdbcTemplate;

    /**
     * Is this bean active? I.e. should this part of the subsystem be used?
     */
    private boolean m_active = true;

    public DrupalAuthenticationComponentImpl() {
        super();
    }

    /**
     * Controls whether this bean is active. I.e. should this part of the subsystem be used?
     *
     * @param active <code>true</code> if this bean is active
     */
    public void setActive(boolean active) {
        m_active = active;
    }

    /**
     * Dependeny Injects the data source to be used for querying Drupal database
     *
     * @param dataSource the data source to use
     */
    public void setDataSource(DataSource dataSource) {
        m_jdbcTemplate = new JdbcTemplate(dataSource);
    }

    /*
    * (non-Javadoc)
    * @see org.alfresco.repo.management.subsystems.ActivateableBean#isActive()
    */
    public boolean isActive() {
        return m_active;
    }

    /**
     * Authenticate against the Drupal database
     *
     * @param userName the username to authenticate
     * @param password the password to authenticate (passed in as plain text)
     * @throws AuthenticationException if authentication failed
     */
    @Override
    protected void authenticateImpl(String userName, char[] password) throws AuthenticationException {
        String userPwd = new String(password);

        // Generate an MD5 hash for the password as that is what we get back from Drupal
        // Get the value as hex
        String userPwdMd5 = DigestUtils.md5Hex(userPwd);

        if (logger.isDebugEnabled()) {
            logger.debug("About to authenticate user: " + userName + " with MD5 password: " + userPwdMd5);
        }

        try {
            String drupalPwdMd5 = m_jdbcTemplate.queryForObject(GET_USER_PWD_SQL, new Object[]{userName}, String.class);

            if (logger.isDebugEnabled()) {
                logger.debug("Got MD5 password from Drupal database: " + drupalPwdMd5);
            }

            if (StringUtils.isNotBlank(drupalPwdMd5)) {
                if (MessageDigest.isEqual(userPwdMd5.getBytes(), drupalPwdMd5.getBytes())) {
                    // Authentication has been successful.
                    // Set the current user, they are now authenticated.
                    setCurrentUser(userName);
                } else {
                    throw new AuthenticationException("Access denied for user: " + userName +
                            ", incorrect password provided.");
                }
            } else {
                throw new AuthenticationException(
                        "Password in Drupal database is blank, empty, or null for user: " + userName);
            }
        } catch (DataAccessException dae) {
            throw new AuthenticationException(
                    "Error getting password from Drupal database for user: " + userName +
                            ", user may not exist in the Drupal database", dae);
        }
    }

    @Override
    protected boolean implementationAllowsGuestLogin() {
        return true;
    }
}