Downloading content from alfresco repository via custom Download Webscript

Showing results for 
Search instead for 
Did you mean: 

Downloading content from alfresco repository via custom Download Webscript

2 1 8,202

Alfresco provides Content REST API for downloading the content from repository as given below.

GET /alfresco/service/api/node/content/{store_type}/{store_id}/{id}?a=false&alf_ticket={TICKET}


a: attach. if true, force download of content as attachment. Possible values are true/false
store_type: workspace
store_id: SpacesStore
id: nodeRefId (UUID of the node)

A StoreRef is comprised of:

Store Protocol - that is, the type of store
Store Identifier - the id of the store

Example storeRefs are:

workspace://SpacesStore  (store_type://store_id)
version://versionStore  (store_type://store_id)
archive://SpacesStore  (store_type://store_id)
See here for Content API Webscript definition: content.get.desc.xml

Any external system or client can use this API to download content from Alfresco repository via an authenticated user which would be registered in Alfresco. 

If you want to know how to get auth ticket (alf_ticket) then visit: Alfresco Login REST API (

OOTB Download REST API will allow to download the content to any user who is registered in alfresco, since every user has consumer access to every site by default via "EVERYONE" group. But let's suppose you want to put some kind of restrictions to the Download API. Let's say for example:

1- Allow download if requesting user is authorized to download the content.
2- Want to validate the site level user role e.g. only Managers/Collaborators/Contributors can download, Consumers should not be allowed to download.
3- Want to check if user is part of DOWNLOADERS groups then allow them to download 
and so on. 
There could be many such cases which we can not achieve via OOTB REST API provided by alfresco. If your contents has copyrights you will definitely not allow users to download the content who are unauthorized. 
To handle such scenarios you need to write a custom Download webscript.
Alfresco provides a Webscript called "org.alfresco.repo.web.scripts.content.StreamContent" ( 

By extending this class we can add our custom user validation logic and leave the streaming and download handling part to this OOTB Webscript.
So, let's take a use case where you don't want a consumer user to download the content from a site. To achieve this use case a custom webscript will be written as given below:

package com.github.abhinavmishra14.webscript;

import java.util.Locale;
import java.util.Set;

import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.web.scripts.content.StreamContent;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.InvalidNodeRefException;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptException;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;

* The Class DownloadContentWebscript.

public class DownloadContentWebscript extends StreamContent {

/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(DownloadContentWebscript.class);

/** The content service. */
private ContentService contentService;

/** The authentication service. */
private AuthenticationService authenticationService;

/** The site service. */
private SiteService siteService;

/** The authority service. */
private AuthorityService authorityService;

/* (non-Javadoc)
* @see org.springframework.extensions.webscripts.WebScript#execute(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.WebScriptResponse)

public void execute(final WebScriptRequest request,
final WebScriptResponse response) throws IOException {"Started executing DownloadContentWebscript...");
try {
final NodeRef nodeRef = getParameterAsNodeRef(request, "nodeRef");
final String userName = authenticationService.getCurrentUserName();
if(isNotAuthorised(nodeRef, userName, siteService, permissionService, authorityService)) {
response.getWriter().write("User is unauthorised to download the requested content!");
} else {
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("Processing the download requested by: {}", userName);
final boolean attach = Boolean.valueOf(request.getParameter("attach"));
processDownload(request, response, nodeRef, attach, ContentModel.PROP_CONTENT);
} catch (AccessDeniedException accessDenied) {
LOGGER.error("Access denied while downloading content", accessDenied);
throw new WebScriptException(Status.STATUS_UNAUTHORIZED,
accessDenied.getMessage(), accessDenied);
} catch (IOException | AlfrescoRuntimeException
| InvalidNodeRefException excp) {
LOGGER.error("Exception occurred while downloading content", excp);
throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,
excp.getMessage(), excp);
}"Existing from DownloadContentWebscript...");

* Process download.
* @param request the request
* @param response the response
* @param nodeRef the node ref
* @param attach the attach
* @param propertyQName the property q name
* @throws IOException the IO exception

private void processDownload(final WebScriptRequest request,
final WebScriptResponse response, final NodeRef nodeRef, final boolean attach,
final QName propertyQName) throws IOException {
String userAgent = request.getHeader("User-Agent");
userAgent = StringUtils.isNotBlank(userAgent) ? userAgent.toLowerCase(Locale.ENGLISH) : StringUtils.EMPTY;
final boolean isClientSupported= userAgent.contains("msie")
|| userAgent.contains(" trident/")
|| userAgent.contains(" chrome/")
|| userAgent.contains(" firefox/");

if (attach && isClientSupported) {
String fileName = (String) this.nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
if (userAgent.contains("msie") || userAgent.contains(" trident/")) {
final String mimeType = contentService.getReader(nodeRef, propertyQName).getMimetype();
if (!(this.mimetypeService.getMimetypes(FilenameUtils.getExtension(fileName)).contains(mimeType))) {
fileName = FilenameUtils.removeExtension(fileName)+ FilenameUtils.EXTENSION_SEPARATOR_STR
+ this.mimetypeService.getExtension(mimeType);
streamContent(request, response, nodeRef, propertyQName, attach, fileName, null);
} else {
streamContent(request, response, nodeRef, propertyQName, attach, null, null);

* Create NodeRef instance from a WebScriptRequest parameter.
* @param req the req
* @param paramName the param name
* @return the parameter as node ref

private NodeRef getParameterAsNodeRef(final WebScriptRequest req, final String paramName) {
final String nodeRefStr = StringUtils.trimToNull(req.getParameter(paramName));
if (StringUtils.isBlank(nodeRefStr)) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing " + paramName + " parameter");
if (!NodeRef.isNodeRef(nodeRefStr)) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Incorrect format for " + paramName + " paramater");
final NodeRef nodeRef = new NodeRef(nodeRefStr);
if (!nodeService.exists(nodeRef)) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, paramName + " not found");
return nodeRef;

* Checks if is not authorised.
* @param nodeRef the node ref
* @param userName the user name
* @param siteService the site service
* @param permissionService the permission service
* @param authorityService the authority service
* @return true, if checks if is not authorised

private boolean isNotAuthorised(final NodeRef nodeRef,
final String userName, final SiteService siteService,
final PermissionService permissionService,
final AuthorityService authorityService) {
boolean isNotAuthorised = false;
final SiteInfo siteInfo = siteService.getSite(nodeRef);
// Checking siteInfo, If it is null that means user is not a member of site and
// hence isNotAuthorised is default to false.
if (null != siteInfo) {
if (siteService.isMember(siteInfo.getShortName(), userName)) {
final Set<AccessPermission> permissions = permissionService.getAllSetPermissions(nodeRef);
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("Checking isNotAuthorised, Available access permissions are: {}", permissions);
for (final AccessPermission permission : permissions) {
if (permission.getPermission().equals("SiteConsumer")
|| permission.getPermission().equals("Consumer")) {
if (permission.getAuthorityType().equals("USER")
&& permission.getAuthority().equals(userName)) {
isNotAuthorised = true;
} else if (permission.getAuthorityType().toString().equals("GROUP")) {
//Set run as system user since other users including consumers can not fetch authorities
final Set<String> authorities = authorityService.getAuthoritiesForUser(userName);
//Clear system user context and set original user context
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("Checking permissions at GROUP level, user has following authorities: {}", authorities);
for (final String authority : authorities) {
if (authority.equals(permission.getAuthority())) {
isNotAuthorised = true;
} else {
isNotAuthorised = true;//Not a member in the site.
return isNotAuthorised;

* Sets the content service.
* @param contentService the content service

public void setContentService(final ContentService contentService) {
this.contentService = contentService;

* Sets the authentication service.
* @param authenticationService the authentication service

public void setAuthenticationService(final AuthenticationService authenticationService) {
this.authenticationService = authenticationService;

* Sets the site service.
* @param siteService the site service

public void setSiteService(final SiteService siteService) {
this.siteService = siteService;

* Sets the authority service.
* @param authorityService the authority service

public void setAuthorityService(final AuthorityService authorityService) {
this.authorityService = authorityService;

WebScript Description:

<shortname>Download Content</shortname>
Download Content based on role and permissions check.
nodeRef- NodeRef of the content e.g. workspace://SpacesStore/5cee9f74-eb2a-43a4-965d-6e4fcde4fb9e
attach (Optional)- if true, force download of content as attachment (Possible values are true/false)

Sample URL:

<format default="">argument</format>
<transaction allow="readonly" />

Bean definition:

<bean id="" class="com.github.abhinavmishra14.webscript.DownloadContentWebscript" parent="webscript">
<property name="permissionService" ref="PermissionService" />
<property name="nodeService" ref="NodeService" />
<property name="mimetypeService" ref="MimetypeService" />
<property name="delegate" ref="webscript.content.streamer" />
<property name="repository" ref="repositoryHelper" />

<property name="contentService" ref="ContentService" />
<property name="authenticationService" ref="AuthenticationService" />
<property name="siteService" ref="SiteService" />
<property name="authorityService" ref="AuthorityService"/>
To test the above web-script it is assumed that you have a site where there are users with SiteConsumer/Consumer role.

Test URL:



About the Author
A tech freak, Architect and Consultant (Alfresco Content Services Certified Engineer, Java/J2EE, Webservices, Microservices, AWS CSA, 2x Azure, Docker, MarkLogic). Writes about Alfresco and Java stuffs at Blog ( Visit My Linkedin Profile ( for more details.
1 Comment