Running your code as a different user with Alfresco

Alfresco is using acegisecurity, so every running thread has a security context associated and every line of code runs with the executing user’s credentials.

However sometimes you need to run a custom code with admin credentials or other system user’s credentials. For example in a current project that I am involved in, we created a configuration utility to store our configuration on Alfresco as content nodes, however in order to read the configurations you have to give proper read access to all users, it seems easy but the configuration files are spread across the repository and we don’t want to set permissions on all of them. We just want to read the configuration files as a user that already have read permission for everything. The only way to do that is to change the Authentication object that is in the Context object provided by acegisecurity.

It is pretty straight forward all you have to do is to call net.sf.acegisecurity.context.ContextHolder.setContext with an implementation of net.sf.acegisecurity.context.SecureContext before executing your code.

Or easier, just put your code in org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork and call org.alfresco.repo.security.authentication.AuthenticationUtil.runAs with it. See the following example.

READ  How to increase disk size for VirtualBox VMs.

Leave a Reply

Your email address will not be published. Required fields are marked *