- Spring driven (configure in new web api methods)

- Support for authentication
- HTTP Basic authentication implementation

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@4645 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
David Caruana
2006-12-18 19:32:33 +00:00
parent 5dcea0fbd1
commit 173e38d6ef
9 changed files with 907 additions and 545 deletions

View File

@@ -0,0 +1,34 @@
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN' 'http://www.springframework.org/dtd/spring-beans.dtd'>
<beans>
<!-- -->
<!-- Web API Authentication -->
<!-- -->
<!-- TODO: For now, experiment with HTTP Basic Authentication -->
<alias alias="web.api.Authentication" name="web.api.BasicAuthentication" />
<bean id="web.api.BasicAuthentication" class="org.alfresco.web.api.BasicAuthentication">
<property name="authenticationService" ref="AuthenticationService" />
</bean>
<!-- -->
<!-- Web API Services -->
<!-- -->
<bean id="web.api.TextSearchDescription" class="org.alfresco.web.api.services.TextSearchDescription">
<property name="httpUri" value="/search/textsearchdescription.xml" />
<property name="templateService" ref="TemplateService" />
</bean>
<bean id="web.api.TextSearch" class="org.alfresco.web.api.services.TextSearch">
<property name="httpUri" value="/search/text" />
<property name="serviceRegistry" ref="ServiceRegistry" />
<property name="searchService" ref="SearchService" />
<property name="templateService" ref="TemplateService"/>
</bean>
</beans>

View File

@@ -37,6 +37,16 @@ public class APIRequest extends HttpServletRequestWrapper
// TODO: Complete list... // TODO: Complete list...
} }
/**
* Enumeration of "required" Authentication level
*/
public enum RequiredAuthentication
{
None,
Guest,
User
}
/** /**
* Construct * Construct

View File

@@ -18,8 +18,6 @@ package org.alfresco.web.api;
import java.io.IOException; import java.io.IOException;
import javax.servlet.ServletContext;
/** /**
* API Service * API Service
* *
@@ -29,12 +27,25 @@ public interface APIService
{ {
/** /**
* Initialise service * Gets the required authentication level for execution of this service
* *
* @param context * @return the required authentication level
*/ */
public void init(ServletContext context); public APIRequest.RequiredAuthentication getRequiredAuthentication();
/**
* Gets the HTTP method this service is bound to
*
* @return HTTP method
*/
public APIRequest.HttpMethod getHttpMethod();
/**
* Gets the HTTP uri this service is bound to
*
* @return HTTP uri
*/
public String getHttpUri();
/** /**
* Execute service * Execute service

View File

@@ -0,0 +1,104 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.web.api;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.ApplicationContext;
/**
* Registry of Web API Services methods
*
* @author davidc
*/
public class APIServiceMap
{
// TODO: Support different kinds of uri resolution (e.g. regex:/search/.*)
private List<APIRequest.HttpMethod> methods = new ArrayList<APIRequest.HttpMethod>();
private List<String> uris = new ArrayList<String>();
private List<APIService> services = new ArrayList<APIService>();
/**
* Construct list of API Services
*
* @param context
*/
public APIServiceMap(ApplicationContext context)
{
// locate authentication interceptor
MethodInterceptor authInterceptor = (MethodInterceptor)context.getBean("web.api.Authentication");
// register all API Services
// NOTE: An API Service is one registered in Spring which supports the APIService interface
Map<String, APIService> apiServices = context.getBeansOfType(APIService.class, false, false);
for (Map.Entry<String, APIService> apiService : apiServices.entrySet())
{
APIService service = apiService.getValue();
APIRequest.HttpMethod method = service.getHttpMethod();
String httpUri = service.getHttpUri();
if (httpUri == null || httpUri.length() == 0)
{
throw new APIException("Web API Service " + apiService.getKey() + " does not specify a HTTP URI mapping");
}
if (authInterceptor != null && service.getRequiredAuthentication() != APIRequest.RequiredAuthentication.None)
{
// wrap API Service in appropriate interceptors (e.g. authentication)
ProxyFactory authFactory = new ProxyFactory(service);
authFactory.addAdvice(authInterceptor);
service = (APIService)authFactory.getProxy();
}
methods.add(method);
uris.add(httpUri);
services.add(service);
}
}
/**
* Gets an API Service given an HTTP Method and URI
*
* @param method
* @param uri
* @return
*/
public APIService get(APIRequest.HttpMethod method, String uri)
{
APIService apiService = null;
// TODO: Replace with more efficient approach
for (int i = 0; i < services.size(); i++)
{
if (methods.get(i).equals(method) && uris.get(i).equals(uri))
{
apiService = services.get(i);
break;
}
}
return apiService;
}
}

View File

@@ -17,13 +17,14 @@
package org.alfresco.web.api; package org.alfresco.web.api;
import java.io.IOException; import java.io.IOException;
import java.util.regex.Pattern;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.alfresco.web.app.servlet.BaseServlet; import org.alfresco.web.app.servlet.BaseServlet;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/** /**
@@ -35,14 +36,8 @@ public class APIServlet extends BaseServlet
{ {
private static final long serialVersionUID = 4209892938069597860L; private static final long serialVersionUID = 4209892938069597860L;
// API Services // API Services
// TODO: Define via configuration private APIServiceMap apiServiceMap;
// TODO: Provide mechanism to construct service specific urls (ideally from template)
private static Pattern TEXT_SEARCH_DESCRIPTION_URI = Pattern.compile("/search/textsearchdescription.xml");
private static Pattern SEARCH_URI = Pattern.compile("/search/text");
private static APIService TEXT_SEARCH_DESCRIPTION_SERVICE;
private static APIService TEXT_SEARCH_SERVICE;
@Override @Override
@@ -50,16 +45,14 @@ public class APIServlet extends BaseServlet
{ {
super.init(); super.init();
// TODO: Replace with dispatch mechanism (maybe lazy construct) // Retrieve all web api services and index by http url & http method
TEXT_SEARCH_DESCRIPTION_SERVICE = new TextSearchDescriptionService(); ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
TEXT_SEARCH_DESCRIPTION_SERVICE.init(getServletContext()); apiServiceMap = new APIServiceMap(context);
TEXT_SEARCH_SERVICE = new TextSearchService();
TEXT_SEARCH_SERVICE.init(getServletContext());
} }
// TODO: // TODO:
// - authentication // - authentication (as suggested in http://www.xml.com/pub/a/2003/12/17/dive.html)
// - atom // - atom
// - generator // - generator
// - author (authenticated) // - author (authenticated)
@@ -79,31 +72,24 @@ public class APIServlet extends BaseServlet
APIRequest request = new APIRequest(req); APIRequest request = new APIRequest(req);
APIResponse response = new APIResponse(res); APIResponse response = new APIResponse(res);
// TODO: Handle authentication - HTTP Auth?
// //
// Execute appropriate service // Execute appropriate service
// //
// TODO: Replace with configurable dispatch mechanism based on HTTP method & uri.
// TODO: Handle errors (with appropriate HTTP error responses) // TODO: Handle errors (with appropriate HTTP error responses)
APIRequest.HttpMethod method = request.getHttpMethod(); APIRequest.HttpMethod method = request.getHttpMethod();
String uri = request.getPathInfo(); String uri = request.getPathInfo();
if (method == APIRequest.HttpMethod.GET && TEXT_SEARCH_DESCRIPTION_URI.matcher(uri).matches()) APIService service = apiServiceMap.get(method, uri);
if (service != null)
{ {
TEXT_SEARCH_DESCRIPTION_SERVICE.execute(request, response); service.execute(request, response);
}
else if (method == APIRequest.HttpMethod.GET && SEARCH_URI.matcher(uri).matches())
{
TEXT_SEARCH_SERVICE.execute(request, response);
} }
else else
{ {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} // TODO: add appropriate error detail
}
} }
} }

View File

@@ -0,0 +1,138 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.web.api;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.util.Base64;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* HTTP Basic Authentication Interceptor
*
* @author davidc
*/
public class BasicAuthentication implements MethodInterceptor
{
// dependencies
private AuthenticationService authenticationService;
/**
* @param authenticationService
*/
public void setAuthenticationService(AuthenticationService authenticationService)
{
this.authenticationService = authenticationService;
}
/* (non-Javadoc)
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
public Object invoke(MethodInvocation invocation)
throws Throwable
{
boolean authorized = false;
Object retVal = null;
Object[] args = invocation.getArguments();
APIRequest request = (APIRequest)args[0];
APIService service = (APIService)invocation.getThis();
try
{
//
// validate credentials
//
String authorization = request.getHeader("Authorization");
if ((authorization == null || authorization.length() == 0) && service.getRequiredAuthentication().equals(APIRequest.RequiredAuthentication.Guest))
{
// authenticate as guest, if service allows
authenticationService.authenticateAsGuest();
authorized = true;
}
else if (authorization != null && authorization.length() > 0)
{
try
{
String[] authorizationParts = authorization.split(" ");
if (!authorizationParts[0].equalsIgnoreCase("basic"))
{
throw new APIException("Authorization '" + authorizationParts[0] + "' not supported.");
}
String decodedAuthorisation = new String(Base64.decode(authorizationParts[1]));
String[] parts = decodedAuthorisation.split(":");
if (parts.length == 1)
{
// assume a ticket has been passed
authenticationService.validate(parts[0]);
authorized = true;
}
else
{
// assume username and password passed
if (parts[0].equals(AuthenticationUtil.getGuestUserName()))
{
authenticationService.authenticateAsGuest();
authorized = true;
}
else
{
authenticationService.authenticate(parts[0], parts[1].toCharArray());
authorized = true;
}
}
}
catch(AuthenticationException e)
{
// failed authentication
}
}
//
// execute API service or request authorization
//
if (authorized)
{
retVal = invocation.proceed();
}
else
{
APIResponse response = (APIResponse)args[1];
response.setStatus(401);
response.setHeader("WWW-Authenticate", "Basic realm=\"Alfresco\"");
}
}
finally
{
// clear authentication
// TODO: Consider case where authentication is set before this method is called.
// That shouldn't be the case for the web api.
if (authorized)
{
authenticationService.clearCurrentSecurityContext();
}
}
return retVal;
}
}

View File

@@ -14,7 +14,7 @@
* language governing permissions and limitations under the * language governing permissions and limitations under the
* License. * License.
*/ */
package org.alfresco.web.api; package org.alfresco.web.api.services;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
@@ -22,8 +22,6 @@ import java.io.StringWriter;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.servlet.ServletContext;
import org.alfresco.service.ServiceRegistry; import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.repository.TemplateNode; import org.alfresco.service.cmr.repository.TemplateNode;
@@ -32,8 +30,13 @@ import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.util.ApplicationContextHelper; import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.GUID; import org.alfresco.util.GUID;
import org.alfresco.web.api.APIException;
import org.alfresco.web.api.APIRequest;
import org.alfresco.web.api.APIResponse;
import org.alfresco.web.api.APIService;
import org.alfresco.web.api.APIRequest.HttpMethod;
import org.alfresco.web.api.APIRequest.RequiredAuthentication;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/** /**
@@ -41,7 +44,7 @@ import org.springframework.web.context.support.WebApplicationContextUtils;
* *
* @author davidc * @author davidc
*/ */
public class TextSearchService implements APIService public class TextSearch implements APIService
{ {
// NOTE: startPage and startIndex are 1 offset. // NOTE: startPage and startIndex are 1 offset.
@@ -51,31 +54,68 @@ public class TextSearchService implements APIService
private static final int itemsPerPage = 10; private static final int itemsPerPage = 10;
// dependencies // dependencies
private String uri;
private ServiceRegistry serviceRegistry; private ServiceRegistry serviceRegistry;
private SearchService searchService; private SearchService searchService;
private TemplateService templateService; private TemplateService templateService;
/**
/* (non-Javadoc) * Sets the Http URI
* @see org.alfresco.web.api.APIService#init(javax.servlet.ServletContext) *
* @param uri
*/ */
public void init(ServletContext context) public void setHttpUri(String uri)
{ {
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(context); this.uri = uri;
init(appContext);
} }
/** /**
* Internal initialisation * @param serviceRegistry
*
* @param context
*/ */
private void init(ApplicationContext context) public void setServiceRegistry(ServiceRegistry serviceRegistry)
{ {
serviceRegistry = (ServiceRegistry)context.getBean(ServiceRegistry.SERVICE_REGISTRY); this.serviceRegistry = serviceRegistry;
searchService = (SearchService)context.getBean(ServiceRegistry.SEARCH_SERVICE.getLocalName()); }
templateService = (TemplateService)context.getBean(ServiceRegistry.TEMPLATE_SERVICE.getLocalName());
/**
* @param searchService
*/
public void setSearchService(SearchService searchService)
{
this.searchService = searchService;
}
/**
* @param templateService
*/
public void setTemplateService(TemplateService templateService)
{
this.templateService = templateService;
}
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getRequiredAuthentication()
*/
public RequiredAuthentication getRequiredAuthentication()
{
return APIRequest.RequiredAuthentication.User;
}
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getHttpMethod()
*/
public HttpMethod getHttpMethod()
{
return APIRequest.HttpMethod.GET;
}
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getHttpUri()
*/
public String getHttpUri()
{
return this.uri;
} }
/* (non-Javadoc) /* (non-Javadoc)
@@ -409,8 +449,11 @@ public class TextSearchService implements APIService
throws Exception throws Exception
{ {
ApplicationContext context = ApplicationContextHelper.getApplicationContext(); ApplicationContext context = ApplicationContextHelper.getApplicationContext();
TextSearchService method = new TextSearchService(); TextSearch method = new TextSearch();
method.init(context); method.setServiceRegistry((ServiceRegistry)context.getBean(ServiceRegistry.SERVICE_REGISTRY));
method.setTemplateService((TemplateService)context.getBean(ServiceRegistry.TEMPLATE_SERVICE.getLocalName()));
method.setSearchService((SearchService)context.getBean(ServiceRegistry.SEARCH_SERVICE.getLocalName()));
method.setHttpUri("/search/text");
method.test(); method.test();
} }

View File

@@ -14,18 +14,18 @@
* language governing permissions and limitations under the * language governing permissions and limitations under the
* License. * License.
*/ */
package org.alfresco.web.api; package org.alfresco.web.api.services;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.servlet.ServletContext;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.TemplateService; import org.alfresco.service.cmr.repository.TemplateService;
import org.springframework.context.ApplicationContext; import org.alfresco.web.api.APIRequest;
import org.springframework.web.context.support.WebApplicationContextUtils; import org.alfresco.web.api.APIResponse;
import org.alfresco.web.api.APIService;
import org.alfresco.web.api.APIRequest.HttpMethod;
import org.alfresco.web.api.APIRequest.RequiredAuthentication;
/** /**
@@ -33,18 +33,53 @@ import org.springframework.web.context.support.WebApplicationContextUtils;
* *
* @author davidc * @author davidc
*/ */
public class TextSearchDescriptionService implements APIService public class TextSearchDescription implements APIService
{ {
// dependencies // dependencies
private String uri;
private TemplateService templateService; private TemplateService templateService;
/* (non-Javadoc) /**
* @see org.alfresco.web.api.APIService#init(javax.servlet.ServletContext) * Sets the Http URI
*
* @param uri
*/ */
public void init(ServletContext context) public void setHttpUri(String uri)
{ {
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(context); this.uri = uri;
templateService = (TemplateService)appContext.getBean(ServiceRegistry.TEMPLATE_SERVICE.getLocalName()); }
/**
* @param templateService
*/
public void setTemplateService(TemplateService templateService)
{
this.templateService = templateService;
}
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getRequiredAuthentication()
*/
public RequiredAuthentication getRequiredAuthentication()
{
return APIRequest.RequiredAuthentication.None;
}
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getHttpMethod()
*/
public HttpMethod getHttpMethod()
{
return APIRequest.HttpMethod.GET;
}
/* (non-Javadoc)
* @see org.alfresco.web.api.APIService#getHttpUri()
*/
public String getHttpUri()
{
return this.uri;
} }
/* (non-Javadoc) /* (non-Javadoc)

View File

@@ -59,6 +59,7 @@
<param-value> <param-value>
classpath:alfresco/web-client-application-context.xml classpath:alfresco/web-client-application-context.xml
classpath:web-services-application-context.xml classpath:web-services-application-context.xml
classpath:alfresco/web-api-application-context.xml
classpath:alfresco/application-context.xml classpath:alfresco/application-context.xml
</param-value> </param-value>
<description>Spring config file locations</description> <description>Spring config file locations</description>