Development in Alfresco: How to run processes with Administrator privileges

/ / Blog, Digital Development en, Document Management
Alfresco BeeCon 2016 could be held in Spain
Our impressions of the Global Activiti User Day

Sometimes, you need to have Administrator privileges to do certain operations in Alfresco. Here we go over the various techniques that exist in the different Alfresco APIs to achieve Admin privileges.

From Java

1. Using AuthenticationUtil.RunAsWork

AuthenticationUtil.runAsSystem(
        new AuthenticationUtil.RunAsWork<Object>() {

            public Object doWork() throws Exception {

                // ...code to be run as Admin...
                return null;

            }
        }
);

2. Using AuthenticationUtil.setRunAsUserSystem

AuthenticationUtil.pushAuthentication();
try {
    AuthenticationUtil.setRunAsUserSystem();
    // ...code to be run as Admin...
} finally {
    AuthenticationUtil.popAuthentication();
}

3. Or alternatively using AuthenticationUtil.setRunAsUserSystem

try {
    AuthenticationUtil.setRunAsUserSystem();
    // ...code to be run as Admin...
} finally {
    AuthenticationUtil.clearCurrentSecurityContext();
}

From JavaScript on the server

Using your own RunAs script (source code based on Fabio Strozzi)

1. Run a JavaScript RunAs root object

package es.keensoft.alfresco.script.RunAs;

public class RunAs extends BaseScopableProcessorExtension {
    public void work(final Function func) {
        final Context cx = Context.getCurrentContext();
        final Scriptable scope = getScope();

        RunAsWork<Object> raw = new RunAsWork<Object>() {
            public Object doWork() throws Exception {
                func.call(cx, scope, scope, new Object[] {});
                return null;
            }
        };

        AuthenticationUtil.runAs(raw, AuthenticationUtil.getAdminUserName());
    }
}

2. Declare the Spring bean to make it available in the Scripts API

<beans>
    <bean id="RunAs" parent="baseJavaScriptExtension" class="es.keensoft.alfresco.script.RunAs">
        <property name="extensionName">
            <value>runAs</value>
        </property>
    </bean>
</beans>

3. Use it in any JavaScript

function main() {
    var f = function() {
        // ...code to be run as Admin...
    };
    runAs.work(f);
}

main();

In a WebScript descriptor

<webscript>
  <shortname>Test</shortname>
  <description>Test</description>
  <url>/test</url>
  <format default="html">argument</format>
  <!-- Use runas="admin" attribute -->
  <authentication runas="admin">user</authentication>
  <transaction>required</transaction>
</webscript>

From the JavaScript client

Not available

From a CMIS client

Not available but using Alfresco tickets and SSO integration (CMIS-887), it is possible to achieve similar performance.

Unidad de negocio, keensoft