geode-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From tush...@apache.org
Subject [1/6] incubator-geode git commit: GEODE-77 : Integrated Security Code Merge Review board url : https://reviews.apache.org/r/37209/
Date Thu, 27 Aug 2015 12:27:17 GMT
Repository: incubator-geode
Updated Branches:
  refs/heads/feature/GEODE-17 [created] d511979ef


http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/PdxBasedCrudController.java
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/PdxBasedCrudController.java b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/PdxBasedCrudController.java
index 96551c6..5c36acb 100644
--- a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/PdxBasedCrudController.java
+++ b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/PdxBasedCrudController.java
@@ -10,6 +10,7 @@ package com.gemstone.gemfire.rest.internal.web.controllers;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 import org.apache.logging.log4j.Logger;
 import org.springframework.http.HttpHeaders;
@@ -24,12 +25,17 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 
+import com.gemstone.gemfire.cache.operations.PutOperationContext;
 import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.security.AuthorizeRequest;
 import com.gemstone.gemfire.internal.util.ArrayUtils;
 import com.gemstone.gemfire.rest.internal.web.controllers.support.JSONTypes;
 import com.gemstone.gemfire.rest.internal.web.controllers.support.RegionData;
 import com.gemstone.gemfire.rest.internal.web.controllers.support.RegionEntryData;
 import com.gemstone.gemfire.rest.internal.web.exception.ResourceNotFoundException;
+import com.gemstone.gemfire.rest.internal.web.security.AuthorizationProvider;
+import com.gemstone.gemfire.rest.internal.web.security.RestRequestFilter;
+import com.gemstone.gemfire.security.NotAuthorizedException;
 import com.wordnik.swagger.annotations.Api;
 import com.wordnik.swagger.annotations.ApiOperation;
 import com.wordnik.swagger.annotations.ApiResponse;
@@ -95,8 +101,23 @@ public class PdxBasedCrudController extends CommonCrudController {
           json, region, key);
     }
     region = decode(region);
-    Object existingPdxObj = null;
     
+    final HttpHeaders headers = new HttpHeaders();
+    headers.setLocation(toUri(region, key));
+    
+    //Do request (Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        //TODO: add isJson type in OperationContext
+        AuthorizationProvider.putAuthorize(region, key, json, true/*isJson*/, null, PutOperationContext.CREATE);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
+    Object existingPdxObj = null;
     //Check whether the user has supplied single JSON doc or Array of JSON docs  
     final JSONTypes jsonType = validateJsonAndFindType(json);
     if(JSONTypes.JSON_ARRAY.equals(jsonType)){
@@ -105,9 +126,6 @@ public class PdxBasedCrudController extends CommonCrudController {
       existingPdxObj = postValue(region, key, convert(json));  
     }
     
-    final HttpHeaders headers = new HttpHeaders();
-    headers.setLocation(toUri(region, key));
-    
     if (existingPdxObj != null) {
       final RegionEntryData<Object> data = new RegionEntryData<Object>(region);
       data.add(existingPdxObj);
@@ -144,16 +162,38 @@ public class PdxBasedCrudController extends CommonCrudController {
     }
     region = decode(region);
       
+    final HttpHeaders headers = new HttpHeaders();
+   
+    //Do request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        AuthorizationProvider.getAllAuthorize(region, getRegion(region).keySet(), null);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
     Map<Object, Object> valueObjs = null;
     final RegionData<Object> data = new RegionData<Object>(region);
-
-    final HttpHeaders headers = new HttpHeaders();
+    
     String keyList = null;
     int regionSize = getRegion(region).size();
     List<Object> keys = new ArrayList<Object>(regionSize);
     List<Object> values = new ArrayList<Object>(regionSize);
     
     for (Map.Entry<Object, Object> entry : getValues(region).entrySet() ) {
+      //Do post authorization if security is enabled.
+      if(AuthorizationProvider.isSecurityEnabled()){
+        try{
+          AuthorizationProvider.getAuthorizePP(region, entry.getKey(), entry.getValue());
+        }catch(NotAuthorizedException nae) {
+          //Sending UNAUTHORIZED response, if any one of the key has UNAUTHORIZED access configured.
+          return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+        }
+      }
+      
       Object value = entry.getValue();
       if (value != null) {
         keys.add(entry.getKey());
@@ -170,7 +210,7 @@ public class PdxBasedCrudController extends CommonCrudController {
         if(maxLimit < 0){
           String errorMessage = String.format("Negative limit param (%1$s) is not valid!", maxLimit);
           return new ResponseEntity<String>(
-              convertErrorAsJson(errorMessage), HttpStatus.BAD_REQUEST);
+              convertErrorAsJson(errorMessage), headers, HttpStatus.BAD_REQUEST);
         }
         
         int mapSize = keys.size();
@@ -187,7 +227,7 @@ public class PdxBasedCrudController extends CommonCrudController {
         // for BAD_REQUEST
         String errorMessage = String.format("limit param (%1$s) is not valid!", limit);
         return new ResponseEntity<String>(
-            convertErrorAsJson(errorMessage), HttpStatus.BAD_REQUEST);
+            convertErrorAsJson(errorMessage), headers, HttpStatus.BAD_REQUEST);
       }  
     } 
     
@@ -227,6 +267,17 @@ public class PdxBasedCrudController extends CommonCrudController {
     final HttpHeaders headers = new HttpHeaders();
     region = decode(region);
     
+    //Do request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        AuthorizationProvider.getAuthorize(region, keys, null);
+      } catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
     if (keys.length == 1) { 
       /* GET op on single key */
       Object value = getValue(region, keys[0]);
@@ -235,6 +286,15 @@ public class PdxBasedCrudController extends CommonCrudController {
         throw new ResourceNotFoundException(String.format("Key (%1$s) does not exist for region (%2$s) in cache!", keys[0], region));
       }
       
+      //Do post authorization if security is enabled.
+      if(AuthorizationProvider.isSecurityEnabled()){
+        try{
+          AuthorizationProvider.getAuthorizePP(region, keys[0], value);
+        }catch(NotAuthorizedException nae) {
+          return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+        }
+      }
+      
       final RegionEntryData<Object> data = new RegionEntryData<Object>(region);
       headers.set("Content-Location", toUri(region, keys[0]).toASCIIString());
       data.add(value);
@@ -246,7 +306,7 @@ public class PdxBasedCrudController extends CommonCrudController {
           && !(ignoreMissingKey.equalsIgnoreCase("true") || ignoreMissingKey.equalsIgnoreCase("false"))){
         String errorMessage = String.format("ignoreMissingKey param (%1$s) is not valid. valid usage is ignoreMissingKey=true!", ignoreMissingKey);
         return new ResponseEntity<String>(
-            convertErrorAsJson(errorMessage), HttpStatus.BAD_REQUEST);
+            convertErrorAsJson(errorMessage), headers, HttpStatus.BAD_REQUEST);
       }
       
       if(!("true".equalsIgnoreCase(ignoreMissingKey))) { 
@@ -259,7 +319,18 @@ public class PdxBasedCrudController extends CommonCrudController {
       }  
       
       final Map<Object, Object> valueObjs = getValues(region, keys);
-
+      
+      //Do post authorization if security is enabled.
+      if(AuthorizationProvider.isSecurityEnabled()){
+        for (Map.Entry<Object, Object> entry : valueObjs.entrySet() ) {
+          try{
+            AuthorizationProvider.getAuthorizePP(region, entry.getKey(), entry.getValue());
+          }catch(NotAuthorizedException nae) {
+            return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+          }
+        }
+      }
+      
       // Do we need to remove null values from Map..?
       // To Remove null value entries from map.
       // valueObjs.values().removeAll(Collections.singleton(null));
@@ -306,14 +377,33 @@ public class PdxBasedCrudController extends CommonCrudController {
     if(logger.isDebugEnabled()){
       logger.debug("updating key(s) for region ({}) ", region);
     }
+    
     region = decode(region);
+    HttpHeaders headers = new HttpHeaders();
+    
+    //Do request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        //TODO: add isJson type in OperationContext
+        if(keys.length > 1){
+          AuthorizationProvider.putAllAuthorize(region, json, null);
+        }else {
+          //TODO: add isJson type in OperationContext
+          AuthorizationProvider.putAuthorize(region, keys[0], json, false /*isObject*/, /*isJson,*/ null, PutOperationContext.UPDATE);
+        }
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
     
     if(keys.length > 1){
       //putAll case
-      return updateMultipleKeys(region, keys, json);
+      return updateMultipleKeys(region, keys, json, headers);
     } else {
       //put case
-      return updateSingleKey(region, keys[0], json, opValue);
+      return updateSingleKey(region, keys[0], json, opValue, headers);
     }
   }
     
@@ -335,9 +425,9 @@ public class PdxBasedCrudController extends CommonCrudController {
       logger.debug("Determining the number of entries in Region ({})...", region);
     }
     region = decode(region);
-      
-    final HttpHeaders headers = new HttpHeaders();
+    //Not Authorized at REST APIs level as even client-server does not provide authz  
     
+    final HttpHeaders headers = new HttpHeaders();
     headers.set("Resource-Count", String.valueOf(getRegion(region).size()) );
     return new ResponseEntity<RegionData<?>>(headers, HttpStatus.OK);
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/QueryAccessController.java
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/QueryAccessController.java b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/QueryAccessController.java
index b20c849..808cb07 100644
--- a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/QueryAccessController.java
+++ b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/QueryAccessController.java
@@ -8,6 +8,7 @@
 
 package com.gemstone.gemfire.rest.internal.web.controllers;
 
+import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 
 import org.apache.logging.log4j.Logger;
@@ -25,6 +26,10 @@ import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.bind.annotation.ResponseStatus;
 
 import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.operations.OperationContext;
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.cache.operations.PutOperationContext;
+import com.gemstone.gemfire.cache.operations.QueryOperationContext;
 import com.gemstone.gemfire.cache.query.FunctionDomainException;
 import com.gemstone.gemfire.cache.query.NameResolutionException;
 import com.gemstone.gemfire.cache.query.Query;
@@ -37,8 +42,10 @@ import com.gemstone.gemfire.cache.query.internal.DefaultQuery;
 import com.gemstone.gemfire.internal.logging.LogService;
 import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
 import com.gemstone.gemfire.rest.internal.web.exception.ResourceNotFoundException;
+import com.gemstone.gemfire.rest.internal.web.security.AuthorizationProvider;
 import com.gemstone.gemfire.rest.internal.web.util.JSONUtils;
 import com.gemstone.gemfire.rest.internal.web.util.ValidationUtils;
+import com.gemstone.gemfire.security.NotAuthorizedException;
 import com.wordnik.swagger.annotations.Api;
 import com.wordnik.swagger.annotations.ApiOperation;
 import com.wordnik.swagger.annotations.ApiResponse;
@@ -98,12 +105,24 @@ public class QueryAccessController extends AbstractBaseController {
     if (logger.isDebugEnabled()) {
       logger.debug("Listing all parameterized Queries in GemFire...");
     }
+  
+    final HttpHeaders headers = new HttpHeaders();  
+    headers.setLocation(toUri("queries"));
     
-    final Region<String, String> parameterizedQueryRegion = getQueryStore(PARAMETERIZED_QUERIES_REGION);
+    //Do request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        AuthorizationProvider.listQueriesAuthorize(OperationCode.LIST, true, "LIST_QUERIES");
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
     
+    final Region<String, String> parameterizedQueryRegion = getQueryStore(PARAMETERIZED_QUERIES_REGION);    
     String queryListAsJson =  JSONUtils.formulateJsonForListQueriesCall(parameterizedQueryRegion);
-    final HttpHeaders headers = new HttpHeaders();  
-    headers.setLocation(toUri("queries"));
+
     return new ResponseEntity<String>(queryListAsJson, headers, HttpStatus.OK);
   } 
   
@@ -134,13 +153,25 @@ public class QueryAccessController extends AbstractBaseController {
     if (logger.isDebugEnabled()) {
       logger.debug("Creating a named, parameterized Query ({}) with ID ({})...", oqlStatement, queryId);
     }
-
-    // store the compiled OQL statement with 'queryId' as the Key into the hidden, ParameterizedQueries Region...
-    final String existingOql = createNamedQuery(PARAMETERIZED_QUERIES_REGION, queryId, oqlStatement);
-
+    
     final HttpHeaders headers = new HttpHeaders();
     headers.setLocation(toUri("queries", queryId));
-
+    
+    
+    //Do request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        AuthorizationProvider.createQueryAuthorize(OperationCode.CREATE_QUERY, true, "CREATE_QUERY", queryId, oqlStatement);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
+    // store the compiled OQL statement with 'queryId' as the Key into the hidden, ParameterizedQueries Region...
+    final String existingOql = createNamedQuery(PARAMETERIZED_QUERIES_REGION, queryId, oqlStatement);
+    
     if (existingOql != null) {
       headers.setContentType(MediaType.APPLICATION_JSON);
       return new ResponseEntity<String>(JSONUtils.formulateJsonForExistingQuery(queryId, existingOql), headers, HttpStatus.CONFLICT);
@@ -171,14 +202,38 @@ public class QueryAccessController extends AbstractBaseController {
     if (logger.isDebugEnabled()) {
       logger.debug("Running an adhoc Query ({})...", oql);
     }
+    
+    HttpHeaders headers = new HttpHeaders();
     oql = decode(oql);
     final Query query = getQueryService().newQuery(oql);
     
+    Set regionNames = ((DefaultQuery)query).getRegionsInQuery(null);
+    
+    //Do request(Pre) authorization if security is enabled.
+    QueryOperationContext queryAuthzContext = null;
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        queryAuthzContext = AuthorizationProvider.queryAuthorize(oql, regionNames, null);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
     // NOTE Query.execute throws many checked Exceptions; let the BaseControllerAdvice Exception handlers catch
     // and handle the Exceptions appropriately (500 Server Error)!
     try {
       Object queryResult =  query.execute();
-      return processQueryResponse(queryResult, "adhoc?q=" + oql);
+      
+      //Post authorization
+      if(AuthorizationProvider.isSecurityEnabled()){
+        queryAuthzContext = AuthorizationProvider.queryAuthorizePP(oql, regionNames, queryResult, queryAuthzContext, null);
+        if(queryAuthzContext != null){
+          queryResult = queryAuthzContext.getQueryResult();
+        }
+      }
+      return processQueryResponse(queryResult, "adhoc?q=" + oql, headers);
     } catch (FunctionDomainException fde) {
       throw new GemfireRestException("A function was applied to a parameter that is improper for that function!", fde);
     } catch (TypeMismatchException tme) {
@@ -227,6 +282,7 @@ public class QueryAccessController extends AbstractBaseController {
       logger.debug("Running named Query with ID ({})...", queryId);
     }
     queryId = decode(queryId);
+    HttpHeaders headers = new HttpHeaders();
     
     if (arguments != null) {
       // Its a compiled query.
@@ -234,11 +290,10 @@ public class QueryAccessController extends AbstractBaseController {
       //Convert arguments into Object[]
       Object args[] = jsonToObjectArray(arguments);
       
+      final String oql = getValue(PARAMETERIZED_QUERIES_REGION, queryId);
       Query compiledQuery = compiledQueries.get(queryId);
       if (compiledQuery == null) {
         // This is first time the query is seen by this server.
-        final String oql = getValue(PARAMETERIZED_QUERIES_REGION, queryId);
-        
         ValidationUtils.returnValueThrowOnNull(oql, new ResourceNotFoundException(
           String.format("No Query with ID (%1$s) was found!", queryId)));
         try {   
@@ -248,11 +303,35 @@ public class QueryAccessController extends AbstractBaseController {
         }
         compiledQueries.putIfAbsent(queryId, (DefaultQuery)compiledQuery);
       }  
-       // NOTE Query.execute throws many checked Exceptions; let the BaseControllerAdvice Exception handlers catch
+       
+      Set regionNames = ((DefaultQuery)compiledQuery).getRegionsInQuery(args);
+      
+      //Do request(Pre) authorization if security is enabled.
+      QueryOperationContext queryAuthzContext = null;
+      if(AuthorizationProvider.isSecurityEnabled()){
+        setAuthTokenHeader(headers);
+        AuthorizationProvider.init();
+        try{
+          queryAuthzContext= AuthorizationProvider.queryAuthorize(oql, regionNames, args);
+        }catch(NotAuthorizedException nae) {
+          return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+        }
+      }
+      
+      // NOTE Query.execute throws many checked Exceptions; let the BaseControllerAdvice Exception handlers catch
        // and handle the Exceptions appropriately (500 Server Error)!
        try {
          Object queryResult =  compiledQuery.execute(args);
-         return processQueryResponse(queryResult, queryId);
+         
+         //Post authorization
+         if(AuthorizationProvider.isSecurityEnabled()){
+           queryAuthzContext = AuthorizationProvider.queryAuthorizePP(oql, regionNames, queryResult, queryAuthzContext, args);
+           if(queryAuthzContext != null){
+             queryResult = queryAuthzContext.getQueryResult();
+           }
+         }
+         
+         return processQueryResponse(queryResult, queryId, headers);
        } catch (FunctionDomainException fde) {
          throw new GemfireRestException("A function was applied to a parameter that is improper for that function!", fde);
        } catch (TypeMismatchException tme) {
@@ -299,17 +378,30 @@ public class QueryAccessController extends AbstractBaseController {
                                    @RequestBody(required = false) final String oqlInBody) {
     
     final String oqlStatement = validateQuery(oqlInUrl, oqlInBody);
-
+    
     if (logger.isDebugEnabled()) {
       logger.debug("Updating a named, parameterized Query ({}) with ID ({})...", oqlStatement, queryId);
     }
-
+    
+    HttpHeaders headers = new HttpHeaders();
+    
+    //Do request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        AuthorizationProvider.updateQueryAuthorize(OperationCode.UPDATE_QUERY, true, "UPDATE_QUERY", queryId, oqlStatement);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
     // update the OQL statement with 'queryId' as the Key into the hidden, ParameterizedQueries Region...
     checkForQueryIdExist(PARAMETERIZED_QUERIES_REGION, queryId);
     updateNamedQuery(PARAMETERIZED_QUERIES_REGION, queryId, oqlStatement);
     compiledQueries.remove(queryId);
 
-    return new ResponseEntity<Object>(HttpStatus.OK);
+    return new ResponseEntity<Object>(headers, HttpStatus.OK);
   }
 
   //delete named, parameterized query
@@ -334,11 +426,24 @@ public class QueryAccessController extends AbstractBaseController {
       logger.debug("Deleting a named, parameterized Query with ID ({}).", queryId);
     }
     
+    HttpHeaders headers = new HttpHeaders();
+    
+    //Do request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        AuthorizationProvider.deleteQueryAuthorize(OperationCode.DELETE_QUERY, true, "DELETE_QUERY", queryId);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
     //delete the OQL statement with 'queryId' as the Key into the hidden,
     // ParameterizedQueries Region...
     deleteNamedQuery(PARAMETERIZED_QUERIES_REGION, queryId);
     compiledQueries.remove(queryId);
-    return new ResponseEntity<Object>(HttpStatus.OK);
+    return new ResponseEntity<Object>(headers, HttpStatus.OK);
   }
   
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/AuthorizationProvider.java
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/AuthorizationProvider.java b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/AuthorizationProvider.java
new file mode 100644
index 0000000..f1cd7cc
--- /dev/null
+++ b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/AuthorizationProvider.java
@@ -0,0 +1,295 @@
+package com.gemstone.gemfire.rest.internal.web.security;
+
+import java.lang.reflect.InvocationTargetException;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.operations.ExecuteFunctionOperationContext;
+import com.gemstone.gemfire.cache.operations.OperationContext;
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.cache.operations.QueryOperationContext;
+import com.gemstone.gemfire.cache.operations.RestAPIsOperationContext;
+import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
+import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+import com.gemstone.gemfire.internal.cache.tier.sockets.ClientProxyMembershipID;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.security.AuthorizeRequest;
+import com.gemstone.gemfire.internal.security.AuthorizeRequestPP;
+import com.gemstone.gemfire.management.internal.RestAgent;
+import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
+import com.gemstone.gemfire.security.AccessControl;
+import com.gemstone.gemfire.security.NotAuthorizedException;
+
+public class AuthorizationProvider {
+  
+  //private static ConcurrentHashMap<String, AuthorizeRequest> tokenToAuthzRequestMap = new ConcurrentHashMap<String, AuthorizeRequest>();
+  //protected static final String AUTH_METADATA_REGION = "__TokenToAuthzRequest__";
+  
+  public static void init(){
+    
+    if(isSecurityEnabled() == false)
+      return;
+    
+    Map<String, Object> envMap = (Map<String, Object>)RestRequestFilter.getEnvironment();
+    String authToken = getAuthToken();
+    Principal principal = (Principal)envMap.get("principal");
+    
+    final Region<String, List<Object>> tokenToAuthzRequestRegion = RestAgent.getAuthzRegion(RestAgent.AUTH_METADATA_REGION);
+    
+    if(!tokenToAuthzRequestRegion.containsKey(authToken)){
+      //Step-2 initialize access-control for the principal. 
+      //Create the AuthorizeRequest instance and store it.(key: token, value: AuthorizeRequest)
+      //String acMethodCreateName = "templates.security.DummyAuthorization.create";
+      InternalDistributedSystem ids = InternalDistributedSystem.getConnectedInstance();
+      
+      String acMethodCreateName = ids.getProperties()
+                             .getProperty(DistributionConfig.SECURITY_CLIENT_ACCESSOR_NAME);
+      
+      String postAuthzFactoryName = ids.getProperties()
+                             .getProperty(DistributionConfig.SECURITY_CLIENT_ACCESSOR_PP_NAME);
+      
+      AccessControl authz = null;
+      //TODO: Discuss about, what should be the distributed member for the REST client
+      DistributedMember dm = null;
+      AuthorizeRequest authzRequest = null;
+      AuthorizeRequestPP postAuthzRequest = null;
+      List<Object> authzObjects = new ArrayList<Object>();
+      
+      //Pre authorization initialization.
+      if (acMethodCreateName != null && acMethodCreateName.length() > 0) {
+        try {
+          // AccessControl is instantiated and initialized here.
+          authzRequest = new AuthorizeRequest(acMethodCreateName, dm,
+               principal, GemFireCacheImpl.getInstance());
+          
+        }catch (NotAuthorizedException nae) {
+          throw new NotAuthorizedException("Not Authorized to perform operation!");
+        }catch (ClassNotFoundException cnf) {
+          throw new GemfireRestException("Server has encountered the problem while initializing the Authorization callbacks!");
+        }catch (NoSuchMethodException nsm) {
+          throw new GemfireRestException("Server has encountered the problem while initializing the Authorization callbacks!");
+        }catch (IllegalAccessException iae) {
+          throw new GemfireRestException("Server has encountered the problem while initializing the Authorization callbacks!");
+        }catch (InvocationTargetException ite) {
+          throw new GemfireRestException("Server has encountered the problem while initializing the Authorization callbacks!");
+        }
+      }
+      authzObjects.add(0, authzRequest);
+      
+      //Post authorization initialization.
+      if (postAuthzFactoryName != null && postAuthzFactoryName.length() > 0) {
+        try{ 
+          postAuthzRequest = new AuthorizeRequestPP(
+                    postAuthzFactoryName, ClientProxyMembershipID.getNewProxyMembership(GemFireCacheImpl.getInstance().getDistributedSystem()), principal, GemFireCacheImpl.getInstance());
+          
+          //TODO: Discuss on ClientProxyMembershipID() for REST CLIENTs
+        }catch (NotAuthorizedException nae) {
+          throw new NotAuthorizedException("Not Authorized to perform operation!");
+        }catch (ClassNotFoundException cnf) {
+          throw new GemfireRestException("Server has encountered the problem while initializing the Authorization callbacks!");
+        }catch (NoSuchMethodException nsm) {
+          throw new GemfireRestException("Server has encountered the problem while initializing the Authorization callbacks!");
+        }catch (IllegalAccessException iae) {
+          throw new GemfireRestException("Server has encountered the problem while initializing the Authorization callbacks!");
+        }catch (InvocationTargetException ite) {
+          throw new GemfireRestException("Server has encountered the problem while initializing the Authorization callbacks!");
+        }
+      }
+      authzObjects.add(1, postAuthzRequest);
+      
+      tokenToAuthzRequestRegion.put(authToken, authzObjects);
+    }
+  }
+  
+  public static void listRegionsAuthorize(OperationCode opCode, boolean isRestOperation, String opType)throws NotAuthorizedException {
+    RestAPIsOperationContext restContext = new RestAPIsOperationContext(opCode, isRestOperation);
+    authorizeRestOperation(null/*regionName*/, restContext, opType);
+  }
+  
+  public static void keySetAuthorize(String region){ 
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null){
+      ar.keySetAuthorize(region);
+    }
+  }
+  
+  public static void deleteAuthorize(String region, final String[] keys, Object callbackArg){
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null) {
+      for(final Object key : keys){
+        ar.destroyAuthorize(region, key, null);
+      }
+    }
+  }
+  
+  public static void deleteAllAuthorize(String region, Object callbackArg){
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null){
+      ar.clearAuthorize(region, callbackArg);
+    }
+  }
+  
+  public static void putAuthorize(String regionName, String key,
+    String json, boolean isObject, Object callbackArg, byte opType){
+    //TODO: add isJson, similar to isObject
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null){
+      ar.putAuthorize(regionName, key, json, isObject, /*isJson*/ callbackArg, opType);
+    }
+  }
+  
+  public static void putAuthorizePP(String regionName, String key,
+    String json, boolean isObject, Object callbackArg, byte opType){
+    //TODO: add isJson, similar to isObject
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null){
+      ar.putAuthorize(regionName, key, json, isObject, /*isJson*/ callbackArg, opType);
+    }
+  }
+  
+  public static void getAllAuthorize(String regionName, Set allKeys, Object callbackArg ){
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null) {
+      for(final Object key : allKeys){
+        ar.getAuthorize(regionName, key, callbackArg);
+      }
+    }  
+  }
+  
+  public static void getAuthorize(String regionName, String[] keys, Object callbackArg ){
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null) {
+      for(final Object key : keys){
+        ar.getAuthorize(regionName, key, callbackArg);
+      }
+    }
+  }
+
+  public static void putAllAuthorize(String regionName, String json, Object callbackArg){
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null) {
+      //TODO: add support for passing json array. isJson=true
+      //ar.putAllAuthorize(regionName, json, callbackArg);
+    }
+  }
+  
+  public static QueryOperationContext queryAuthorize(String queryString, Set regionNames, Object[] queryParams){
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null) {
+      return ar.queryAuthorize(queryString, regionNames, queryParams);
+    }
+    return null;
+  }
+  
+  public static QueryOperationContext queryAuthorizePP(String queryString, Set regionNames, Object queryResult, QueryOperationContext queryContext, Object[] queryParams){
+    AuthorizeRequestPP arPP = RestAgent.getAuthorizeRequestPP(getAuthToken());
+    if(arPP != null) {
+      return arPP.queryAuthorize(queryString, regionNames, queryResult, queryContext, queryParams);
+    }
+    return null;
+  }
+  
+  public static void listQueriesAuthorize(OperationCode opCode, boolean isRestOperation, String opType) 
+      throws NotAuthorizedException {
+    RestAPIsOperationContext restContext = new RestAPIsOperationContext(opCode, isRestOperation);
+    authorizeRestOperation(null/*regionName*/, restContext, opType);
+  }
+  
+  public static void createQueryAuthorize(OperationCode opCode, boolean isRestOperation, String opType, String queryId, String oqlStatement) 
+      throws NotAuthorizedException {
+    RestAPIsOperationContext restContext = new RestAPIsOperationContext(opCode, isRestOperation, queryId, oqlStatement);
+    authorizeRestOperation(null/*regionName*/, restContext, opType);
+  }
+  
+  public static void updateQueryAuthorize(OperationCode opCode, boolean isRestOperation, String opType, String queryId, String oqlStatement) 
+      throws NotAuthorizedException {
+    RestAPIsOperationContext restContext = new RestAPIsOperationContext(opCode, isRestOperation, queryId, oqlStatement);
+    authorizeRestOperation(null/*regionName*/, restContext, opType);
+  }
+  
+  public static void deleteQueryAuthorize(OperationCode opCode, boolean isRestOperation, String opType, String queryId) 
+      throws NotAuthorizedException {
+    RestAPIsOperationContext restContext = new RestAPIsOperationContext(opCode, isRestOperation, queryId, null /*oqlStatement*/);
+    authorizeRestOperation(null/*regionName*/, restContext, opType);
+  }
+ 
+  public static /*RestAPIsOperationContext*/void listFunctionsAuthorize(OperationCode opCode, boolean isRestOperation, String opType) 
+      throws NotAuthorizedException {
+    RestAPIsOperationContext restContext = new RestAPIsOperationContext(opCode, isRestOperation);
+    authorizeRestOperation(null/*regionName*/, restContext, opType);
+  }
+  
+  public static ExecuteFunctionOperationContext executeFunctionAuthorize(String functionName, String region,
+                                              Set keySet, Object arguments, boolean optimizeForWrite){
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null) {
+      return ar.executeFunctionAuthorize(functionName, region, keySet, arguments, optimizeForWrite);
+    }
+    return null;
+  }
+  
+  public static void executeFunctionAuthorizePP(Object oneResult, ExecuteFunctionOperationContext executeContext){
+    AuthorizeRequestPP arPP = RestAgent.getAuthorizeRequestPP(getAuthToken());
+    if(arPP != null) {
+      arPP.executeFunctionAuthorize(oneResult, executeContext);
+    }
+  }
+  
+  private static String getAuthToken(){
+    Map<String, Object> envMap = (Map<String, Object>)RestRequestFilter.getEnvironment();
+    return (String)envMap.get("authToken");
+  }
+  
+  public static boolean isSecurityEnabled(){
+    Map<String, Object> envMap = (Map<String, Object>)RestRequestFilter.getEnvironment();
+    boolean isSecurityEnabled = (boolean) envMap.get("isSecurityEnabled");
+    
+    if(isSecurityEnabled == true) {
+      return true;
+    }
+     
+    return false;
+  }
+  
+  private static void authorizeRestOperation( String regionName, OperationContext restContext, String opType){
+    AuthorizeRequest ar = RestAgent.getAuthorizeRequest(getAuthToken());
+    if(ar != null) {
+      if (!ar.getAuthzCallback().authorizeOperation(null, restContext)) {
+        String errStr = "Not authorized to perfom" +  opType + "operation on the cache";
+        ar.getLogger().warning( LocalizedStrings.TWO_ARG_COLON, new Object[] {ar, errStr});
+        if (ar.isPrincipalSerializable()) {
+          throw new NotAuthorizedException(errStr, ar.getPrincipal());
+        }
+        else {
+          throw new NotAuthorizedException(errStr);
+        }
+      }
+      else {
+        if (ar.getLogger().finestEnabled()) {
+          ar.getLogger().finest(ar.toString()
+              + ": Authorized to perform" + opType + "operation on cache");
+        }
+      } 
+    }
+  }
+  
+  public static void getAuthorizePP(String regionName, Object key, Object result ){
+    AuthorizeRequestPP arPP = RestAgent.getAuthorizeRequestPP(getAuthToken());
+    if(arPP != null) {
+      arPP.getAuthorize(regionName, key, result, true, null);
+    }
+  }
+
+  public static void keySetAuthorizePP(String regionName, Set keySet) {
+    AuthorizeRequestPP arPP = RestAgent.getAuthorizeRequestPP(getAuthToken());
+    if(arPP != null) {
+      arPP.keySetAuthorize(regionName, keySet, null);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/FunctionExecutionPostAuthzRC.java
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/FunctionExecutionPostAuthzRC.java b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/FunctionExecutionPostAuthzRC.java
new file mode 100644
index 0000000..416404d
--- /dev/null
+++ b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/FunctionExecutionPostAuthzRC.java
@@ -0,0 +1,101 @@
+package com.gemstone.gemfire.rest.internal.web.security;
+
+import java.util.ArrayList;
+import java.util.concurrent.TimeUnit;
+
+import com.gemstone.gemfire.cache.execute.Function;
+import com.gemstone.gemfire.cache.execute.FunctionException;
+import com.gemstone.gemfire.cache.execute.ResultCollector;
+import com.gemstone.gemfire.cache.operations.ExecuteFunctionOperationContext;
+import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.security.NotAuthorizedException;
+
+public class FunctionExecutionPostAuthzRC implements ResultCollector {
+
+  private ArrayList<Object> resultList = new ArrayList<Object>();
+  
+  private ExecuteFunctionOperationContext functionAuthzContext;
+  
+  public FunctionExecutionPostAuthzRC() {
+  
+  }
+  
+  public FunctionExecutionPostAuthzRC(ExecuteFunctionOperationContext context) {
+    this.functionAuthzContext = context;
+    this.functionAuthzContext.setIsPostOperation(true);
+  }
+
+  /**
+   * Adds a single function execution result from a remote node to the
+   * ResultCollector
+   * 
+   * @param distributedMember
+   * @param resultOfSingleExecution
+   */
+  public synchronized void addResult(DistributedMember distributedMember,
+      Object resultOfSingleExecution) {
+    //Post authorization here
+    if(AuthorizationProvider.isSecurityEnabled()){
+      try{
+        functionAuthzContext.setResult(resultOfSingleExecution);
+        AuthorizationProvider.executeFunctionAuthorizePP(resultOfSingleExecution, functionAuthzContext);
+      }catch(NotAuthorizedException nae){
+        throw new NotAuthorizedException("Not Authorized to get results!");
+      }
+    }
+    this.resultList.add(functionAuthzContext.getResult() );
+  }
+
+  /**
+   * Waits if necessary for the computation to complete, and then retrieves its
+   * result.<br>
+   * If {@link Function#hasResult()} is false, upon calling
+   * {@link ResultCollector#getResult()} throws {@link FunctionException}.
+   * 
+   * @return the Object computed result
+   * @throws FunctionException
+   *                 if something goes wrong while retrieving the result
+   */
+  public Object getResult() throws FunctionException {
+    return this.resultList; // this is full result
+  }
+
+  /**
+   * Call back provided to caller, which is called after function execution is
+   * complete and caller can retrieve results using
+   * {@link ResultCollector#getResult()}
+   * 
+   */
+  public void endResults() {
+  }
+
+  /**
+   * Waits if necessary for at most the given time for the computation to
+   * complete, and then retrieves its result, if available. <br>
+   * If {@link Function#hasResult()} is false, upon calling
+   * {@link ResultCollector#getResult()} throws {@link FunctionException}.
+   * 
+   * @param timeout
+   *                the maximum time to wait
+   * @param unit
+   *                the time unit of the timeout argument
+   * @return Object computed result
+   * @throws FunctionException
+   *                 if something goes wrong while retrieving the result
+   */
+  public Object getResult(long timeout, TimeUnit unit)
+      throws FunctionException {
+    return this.resultList;
+  }
+
+  /**
+   * GemFire will invoke this method before re-executing function (in case of
+   * Function Execution HA) This is to clear the previous execution results from
+   * the result collector
+   * 
+   */
+  public void clearResults() {
+    this.resultList.clear();
+  }
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/RestRequestFilter.java
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/RestRequestFilter.java b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/RestRequestFilter.java
new file mode 100644
index 0000000..a88c9c1
--- /dev/null
+++ b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/security/RestRequestFilter.java
@@ -0,0 +1,241 @@
+package com.gemstone.gemfire.rest.internal.web.security;
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.security.Principal;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.util.StringUtils;
+
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
+import com.gemstone.gemfire.internal.ClassLoadUtil;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.security.AuthorizeRequest;
+import com.gemstone.gemfire.management.internal.RestAgent;
+import com.gemstone.gemfire.security.AuthenticationFailedException;
+import com.gemstone.gemfire.security.Authenticator;
+import com.gemstone.gemfire.security.TokenService;
+
+public class RestRequestFilter  implements Filter {
+ 
+  public static final String AUTH_TOKEN_HEADER = "security-gfrest-authtoken";
+  public static final String SECURITY_PROPS_PREFIX = "security-"; 
+  
+  public static final String AUTH_TOKEN = "authToken";
+  public static final String AUTH_PRINCIPAL = "principal";
+  public static final String IS_REST_APIS_SECURITY_ENABLED = "isSecurityEnabled";
+  
+  private static final ThreadLocal<Map<String, Object>> ENV = new ThreadLocal<Map<String, Object>>() {
+    @Override
+    protected Map<String, Object> initialValue() {
+      return Collections.emptyMap();
+    }
+  };
+
+  public static Map<String, Object>  getEnvironment() {
+    return ENV.get();
+  }
+
+  private Properties getHeadersInfo(HttpServletRequest request) {
+    
+    Properties props = new Properties();
+
+    Enumeration headerNames = request.getHeaderNames();
+    while (headerNames.hasMoreElements()) {
+      String key = (String) headerNames.nextElement();
+      if(key.startsWith(SECURITY_PROPS_PREFIX)){
+        props.setProperty(key, request.getHeader(key));
+      }
+    }
+
+    return props;
+  }
+  
+  public void init(FilterConfig fConfig) throws ServletException {}
+ 
+  private Principal verifyCredentials(Properties props, InternalDistributedSystem ids){
+              
+    //String authCreateName = "templates.security.DummyAuthenticator.create";
+    String methodName = ids.getProperties()
+                           .getProperty(DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME);
+      
+    Authenticator auth = null;
+    try {
+      if (methodName == null || methodName.length() == 0) {
+        return null;
+      }
+      Method instanceGetter = ClassLoadUtil.methodFromName(methodName);
+      auth = (Authenticator)instanceGetter.invoke(null, (Object[])null);
+      
+    }catch (Exception ex) {
+      throw new AuthenticationFailedException(
+            LocalizedStrings.HandShake_FAILED_TO_ACQUIRE_AUTHENTICATOR_OBJECT.toLocalizedString(), ex);
+    }
+      
+    if (auth == null) {
+      throw new AuthenticationFailedException(
+          LocalizedStrings.HandShake_AUTHENTICATOR_INSTANCE_COULD_NOT_BE_OBTAINED.toLocalizedString()); 
+    }
+    
+    auth.init(props, ids.getLogWriter(), ids.getSecurityLogWriter());
+    Principal principal;
+    try {
+      principal = auth.authenticate(props, ids.getDistributedMember());
+    }catch(AuthenticationFailedException ex){
+      throw ex;
+    }catch (Exception e){
+      throw new AuthenticationFailedException("Authentication Failed", e);
+    }
+    finally {
+      auth.close();
+    }
+       
+    return principal;      
+  }
+     
+  private String generateToken(Principal principal, InternalDistributedSystem ids){
+    
+    String tokenServiceName = ids.getProperties()
+                           .getProperty(DistributionConfig.SECURITY_REST_TOKEN_SERVICE_NAME);
+      
+    TokenService tokenService = null;
+    try {
+      if (tokenServiceName == null || tokenServiceName.length() == 0) {
+        return null;
+      }
+      Method instanceGetter = ClassLoadUtil.methodFromName(tokenServiceName);
+      tokenService = (TokenService)instanceGetter.invoke(null, (Object[])null);
+      
+      return tokenService.generateToken(principal);
+    }catch (Exception ex) {
+      throw new AuthenticationFailedException(
+            "Failed to acquire TokenService object", ex);
+    }
+  }
+  
+  private String validateToken(String authToken, Principal principal, InternalDistributedSystem ids){
+    
+    //String authCreateName = "templates.security.DummyAuthenticator.create";
+    String tokenServiceName = ids.getProperties()
+                           .getProperty(DistributionConfig.SECURITY_REST_TOKEN_SERVICE_NAME);
+      
+    TokenService tokenService = null;
+    try {
+      if (tokenServiceName == null || tokenServiceName.length() == 0) {
+        return null;
+      }
+      
+      Method instanceGetter = ClassLoadUtil.methodFromName(tokenServiceName);
+      tokenService = (TokenService)instanceGetter.invoke(null, (Object[])null);
+      
+      return tokenService.validateToken(authToken, principal);
+    }catch (Exception ex) {
+      //Remove the invalid token from the state
+      RestAgent.closeAuthz(authToken);
+      RestAgent.removeAuthzEntry(authToken);
+      throw new AuthenticationFailedException(
+            "Invalid authentication token found", ex);
+    }
+  }
+  
+
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+    
+    Map<String, Object>  map = new HashMap<String, Object>();
+    boolean isSecurityEnabled = false;
+    
+    InternalDistributedSystem ids = InternalDistributedSystem.getConnectedInstance();
+    
+    String authMethodName = ids.getProperties()
+    .getProperty(DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME);
+    
+    //TODO: find the props on which we can conclude that security is enabled/configured or not!
+    if (!StringUtils.isEmpty(authMethodName)) {
+      //DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME
+      HttpServletRequest httpRequest = (HttpServletRequest) request;
+      HttpServletResponse httpResponse = (HttpServletResponse) response;
+      
+      String authToken = httpRequest.getHeader(AUTH_TOKEN_HEADER);
+      Principal principal= null;
+          
+      if(StringUtils.isEmpty(authToken)){ 
+        //authToken is not present in the REST request.
+        //fetch security headers starting with "security-"
+        Properties props = getHeadersInfo(httpRequest);
+        if(props.size() > 0){
+          //Attempt authentication
+          principal = verifyCredentials(props, ids);
+        
+          authToken =  generateToken(principal, ids); 
+          
+        }else {
+          //If creds or token not present in request header, 401 Authentication required response
+          throw new AuthenticationFailedException("Authentication required.!");
+        }
+      }else { 
+        //Case: Token present in the request header
+        final Region<String, List<Object>> tokenToAuthzRequestRegion = RestAgent.getAuthzRegion(RestAgent.AUTH_METADATA_REGION);
+        //TODO: add getter to fetch principal.
+        principal = RestAgent.getPrincipalForToken(authToken);
+        String refreshedToken = validateToken(authToken, principal, ids);
+        
+        //Check whether TokenService has refreshed the token, If so, Update the AuthZ map
+        if(!authToken.equals(refreshedToken)){
+          List<Object> authObjects= tokenToAuthzRequestRegion.get(authToken);
+          RestAgent.removeAuthzEntry(authToken);
+          RestAgent.addAuthzEntry(refreshedToken, authObjects);
+          authToken = refreshedToken;
+        }
+      }
+      
+      //Add entries in ThreadLocal  
+      map.put(AUTH_TOKEN, authToken);
+      map.put(AUTH_PRINCIPAL, principal);
+      isSecurityEnabled = true;
+    }
+      
+    map.put("isSecurityEnabled", isSecurityEnabled);
+    ENV.set(map);
+    
+    chain.doFilter(request, response);
+  }
+  
+  protected void setAuthTokenHeader(final ServletResponse response) {
+    
+    HttpServletResponse httpResponse = (HttpServletResponse) response;
+    Map<String, Object> envMap = (Map<String, Object>)RestRequestFilter.getEnvironment();
+    boolean isSecurityEnabled = (boolean) envMap.get(IS_REST_APIS_SECURITY_ENABLED);
+    String authToken = (String)envMap.get(AUTH_TOKEN);
+    
+    if(isSecurityEnabled == false)
+      return;
+  
+    httpResponse.addHeader(AUTH_TOKEN_HEADER, authToken);
+  }
+  
+  public void destroy() {}
+    
+  public boolean isValid(String authToken){
+    if(!StringUtils.hasText(authToken))
+    {
+      return false;
+    }
+    return true;
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-web-api/src/main/webapp/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/webapp/WEB-INF/web.xml b/gemfire-web-api/src/main/webapp/WEB-INF/web.xml
index 554ef4b..3997272 100644
--- a/gemfire-web-api/src/main/webapp/WEB-INF/web.xml
+++ b/gemfire-web-api/src/main/webapp/WEB-INF/web.xml
@@ -46,4 +46,14 @@
     <url-pattern>/*</url-pattern>
   </servlet-mapping>
   
+  <filter>
+    <filter-name>restRequestFilter</filter-name>
+    <filter-class>com.gemstone.gemfire.rest.internal.web.security.RestRequestFilter</filter-class>
+  </filter>
+
+  <filter-mapping>
+    <filter-name>restRequestFilter</filter-name>
+    <url-pattern>/*</url-pattern>
+  </filter-mapping>
+
 </web-app>


Mime
View raw message