You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by tu...@apache.org on 2015/08/27 14:27:17 UTC

[1/6] incubator-geode git commit: GEODE-77 : Integrated Security Code Merge Review board url : https://reviews.apache.org/r/37209/

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>


[3/6] incubator-geode git commit: GEODE-77 : Integrated Security Code Merge Review board url : https://reviews.apache.org/r/37209/

Posted by tu...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperationContext.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperationContext.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperationContext.java
index aa1c38c..3801d66 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperationContext.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperationContext.java
@@ -1,187 +1,421 @@
 package com.gemstone.gemfire.management.internal.security;
 
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 import com.gemstone.gemfire.cache.operations.OperationContext;
 
+/**
+ * This is base class for OperationContext for resource (JMX and CLI) operations
+ * 
+ * @author tushark
+ * 
+ * @since 9.0
+ */
 public abstract class ResourceOperationContext extends OperationContext {
-	
-	 public static class ResourceOperationCode {
-		 
-		private static final byte OP_LIST_DS = 1;	
-	    private static final byte OP_READ_DS = 2;
-	    private static final byte OP_SET_DS = 3;
-	    private static final byte OP_ADMIN_DS = 4;
-	    private static final byte OP_CHANGE_ALERT_LEVEL_DS = 5;
-	    private static final byte OP_BACKUP_DS = 6;
-	    private static final byte OP_REMOVE_DISKSTORE_DS = 7;
-	    private static final byte OP_SHUTDOWN_DS = 8;
-	    private static final byte OP_QUERYDATA_DS = 9;
-	    private static final byte OP_REBALANCE_DS = 10;
-	    
-	    private static final byte OP_EXPORT_DATA_REGION = 11;
-	    private static final byte OP_IMPORT_DATA_REGION = 12 ;
-	    private static final byte OP_PUT_REGION = 13;
-	    private static final byte OP_LOCATE_ENTRY_REGION = 14;
-	    
-	    private static final byte OP_PULSE_DASHBOARD = 15;
-	    private static final byte OP_PULSE_DATABROWSER = 16;
-	    private static final byte OP_PULSE_WEBGFSH = 17;
-	    private static final byte OP_PULSE_ADMIN_V1 = 18;
-	    
-	    
-	    private static final ResourceOperationCode[] VALUES = new ResourceOperationCode[20];
-	    private static final Map OperationNameMap = new HashMap();
-	    
-	    public static final ResourceOperationCode LIST_DS = new ResourceOperationCode(ResourceConstants.LIST_DS, OP_LIST_DS);
-	    public static final ResourceOperationCode READ_DS = new ResourceOperationCode(ResourceConstants.READ_DS, OP_READ_DS);
-	    public static final ResourceOperationCode SET_DS = new ResourceOperationCode(ResourceConstants.SET_DS, OP_SET_DS);
-
-	    public static final ResourceOperationCode CHANGE_ALERT_LEVEL_DS = new ResourceOperationCode(ResourceConstants.CHANGE_ALERT_LEVEL_DS, OP_CHANGE_ALERT_LEVEL_DS);
-	    public static final ResourceOperationCode BACKUP_DS = new ResourceOperationCode(ResourceConstants.BACKUP_DS, OP_BACKUP_DS);
-	    public static final ResourceOperationCode REMOVE_DISKSTORE_DS = new ResourceOperationCode(ResourceConstants.REMOVE_DISKSTORE_DS, OP_REMOVE_DISKSTORE_DS);
-	    public static final ResourceOperationCode SHUTDOWN_DS = new ResourceOperationCode(ResourceConstants.SHUTDOWN_DS, OP_SHUTDOWN_DS);
-	    public static final ResourceOperationCode QUERYDATA_DS = new ResourceOperationCode(ResourceConstants.QUERYDATA_DS, OP_QUERYDATA_DS);
-	    public static final ResourceOperationCode REBALANCE_DS = new ResourceOperationCode(ResourceConstants.REBALANCE, OP_REBALANCE_DS);
-	    
-	    public static final ResourceOperationCode EXPORT_DATA_REGION = new ResourceOperationCode(ResourceConstants.EXPORT_DATA, OP_EXPORT_DATA_REGION);
-	    public static final ResourceOperationCode IMPORT_DATA_REGION = new ResourceOperationCode(ResourceConstants.IMPORT_DATA, OP_IMPORT_DATA_REGION);
-	    public static final ResourceOperationCode PUT_REGION = new ResourceOperationCode(ResourceConstants.PUT, OP_PUT_REGION);
-	    public static final ResourceOperationCode LOCATE_ENTRY_REGION = new ResourceOperationCode(ResourceConstants.LOCATE_ENTRY, OP_LOCATE_ENTRY_REGION);	    
-	    
-	    public static final ResourceOperationCode PULSE_DASHBOARD = new ResourceOperationCode(ResourceConstants.PULSE_DASHBOARD, OP_PULSE_DASHBOARD);
-	    public static final ResourceOperationCode PULSE_DATABROWSER = new ResourceOperationCode(ResourceConstants.PULSE_DATABROWSER, OP_PULSE_DATABROWSER);
-	    public static final ResourceOperationCode PULSE_WEBGFSH = new ResourceOperationCode(ResourceConstants.PULSE_WEBGFSH, OP_PULSE_WEBGFSH);
-	    public static final ResourceOperationCode PULSE_ADMIN_V1 = new ResourceOperationCode(ResourceConstants.PULSE_ADMIN_V1, OP_PULSE_ADMIN_V1);
-	    
-	    public static final ResourceOperationCode ADMIN_DS = new ResourceOperationCode(ResourceConstants.ADMIN_DS, OP_ADMIN_DS,
-	    		new ResourceOperationCode[]{
-	          CHANGE_ALERT_LEVEL_DS, 
-	          BACKUP_DS, 
-	          REMOVE_DISKSTORE_DS, 
-	          SHUTDOWN_DS, 
-	          QUERYDATA_DS, 
-	    			REBALANCE_DS, 
-	    			PULSE_DASHBOARD, 
-	    			PULSE_DATABROWSER, 
-	    			PULSE_WEBGFSH, 
-	    			PULSE_ADMIN_V1
-	    		});
-		
-	    
-	    private final String name;
-	    private final byte opCode;
-	    private final ResourceOperationCode[] children;
-	    
-	    private ResourceOperationCode(String name, byte opCode) {
-	      this.name = name;
-	      this.opCode = opCode;
-	      VALUES[opCode] = this;
-	      OperationNameMap.put(name, this);
-	      this.children = null;
-	    }
-	    
-	    private ResourceOperationCode(String name, byte opCode, ResourceOperationCode[] children) {
-		      this.name = name;
-		      this.opCode = opCode;
-		      VALUES[opCode] = this;
-		      OperationNameMap.put(name, this);
-		      this.children = children;
-		}
-	    
-	    
-	    
-	    public ResourceOperationCode[] getChildren() {
-        return children;
+  
+  private boolean isPostOperation=false;
+  private Object opResult = null;
+  
+  public static class ResourceOperationCode {
+    
+    private static final int OP_ALTER_REGION = 1;
+    private static final int OP_ALTER_RUNTIME = 2;
+    private static final int OP_BACKUP_DISKSTORE = 3;
+    private static final int OP_CHANGE_ALERT_LEVEL = 4;
+    private static final int OP_CLOSE_DURABLE_CLIENT = 5;
+    private static final int OP_CLOSE_DURABLE_CQ = 6;
+    private static final int OP_COMPACT_DISKSTORE = 7;
+    private static final int OP_CONFIGURE_PDX = 8;
+    private static final int OP_CREATE_AEQ = 9;
+    private static final int OP_CREATE_DISKSTORE = 10;
+    private static final int OP_CREATE_GW_RECEIVER = 11;
+    private static final int OP_CREATE_GW_SENDER = 12;
+    private static final int OP_CREATE_INDEX = 13;
+    private static final int OP_CREATE_REGION = 14;
+    private static final int OP_DEPLOY = 15;
+    private static final int OP_DESTROY_DISKSTORE = 16;
+    private static final int OP_DESTROY_FUNCTION = 17;
+    private static final int OP_DESTROY_INDEX = 18;
+    private static final int OP_DESTROY_REGION = 19;
+    private static final int OP_EXECUTE_FUNCTION = 20;
+    private static final int OP_EXPORT_CONFIG = 21;
+    private static final int OP_EXPORT_DATA = 22;
+    private static final int OP_EXPORT_LOGS = 23;
+    private static final int OP_EXPORT_OFFLINE_DISKSTORE = 24;
+    private static final int OP_EXPORT_STACKTRACE = 25;
+    private static final int OP_GC = 26;
+    private static final int OP_GET = 27;
+    private static final int OP_IMPORT_CONFIG = 28;
+    private static final int OP_IMPORT_DATA = 29;
+    private static final int OP_LIST_DS = 30;
+    private static final int OP_LOAD_BALANCE_GW_SENDER = 31;
+    private static final int OP_LOCATE_ENTRY = 32;
+    private static final int OP_NETSTAT = 33;
+    private static final int OP_PAUSE_GW_SENDER = 34;
+    private static final int OP_PUT = 35;
+    private static final int OP_QUERY = 36;
+    private static final int OP_REBALANCE = 37;
+    private static final int OP_REMOVE = 38;
+    private static final int OP_RENAME_PDX = 39;
+    private static final int OP_RESUME_GW_SENDER = 40;
+    private static final int OP_REVOKE_MISSING_DISKSTORE = 41;
+    private static final int OP_SHOW_DEADLOCKS = 42;
+    private static final int OP_SHOW_LOG = 43;
+    private static final int OP_SHOW_METRICS = 44;
+    private static final int OP_SHOW_MISSING_DISKSTORES = 45;
+    private static final int OP_SHOW_SUBSCRIPTION_QUEUE_SIZE = 46;
+    private static final int OP_SHUTDOWN = 47;
+    private static final int OP_STOP_GW_RECEIVER = 48;
+    private static final int OP_STOP_GW_SENDER = 49;
+    private static final int OP_UNDEPLOY = 50;
+    private static final int OP_BACKUP_MEMBERS = 51;
+    private static final int OP_ROLL_DISKSTORE = 52;
+    private static final int OP_FORCE_COMPACTION = 53;
+    private static final int OP_FORCE_ROLL = 54;
+    private static final int OP_FLUSH_DISKSTORE = 55;
+    private static final int OP_START_GW_RECEIVER = 56;
+    private static final int OP_START_GW_SENDER = 57;
+    private static final int OP_BECOME_LOCK_GRANTOR = 58;
+    private static final int OP_START_MANAGER = 59;
+    private static final int OP_STOP_MANAGER = 60;
+    private static final int OP_CREATE_MANAGER = 61;
+    private static final int OP_STOP_CONTINUOUS_QUERY = 62;
+    private static final int OP_SET_DISK_USAGE = 63;
+    private static final int OP_CREATE_HDFS_STORE = 64;
+    private static final int OP_ALTER_HDFS_STORE = 65;
+    private static final int OP_DESTROY_HDFS_STORE = 66;
+    
+
+    private static final int OP_PULSE_DASHBOARD = 92;
+    private static final int OP_PULSE_DATABROWSER = 93;
+    private static final int OP_PULSE_WEBGFSH = 94;
+    private static final int OP_PULSE_ADMIN_V1 = 95;
+    
+    private static final int OP_DATA_READ = 96;
+    private static final int OP_DATA_WRITE = 97;
+    private static final int OP_MONITOR = 98;
+    private static final int OP_ADMIN = 99;
+
+    private static final ResourceOperationCode[] VALUES = new ResourceOperationCode[100];
+    private static final Map<String, ResourceOperationCode> OperationNameMap = new HashMap<String, ResourceOperationCode>();
+      
+    
+    public static final ResourceOperationCode ALTER_REGION  = new ResourceOperationCode(ResourceConstants.ALTER_REGION, OP_ALTER_REGION);
+    public static final ResourceOperationCode ALTER_RUNTIME = new ResourceOperationCode(ResourceConstants.ALTER_RUNTIME, OP_ALTER_RUNTIME);
+    public static final ResourceOperationCode BACKUP_DISKSTORE = new ResourceOperationCode(ResourceConstants.BACKUP_DISKSTORE, OP_BACKUP_DISKSTORE);
+    public static final ResourceOperationCode CHANGE_ALERT_LEVEL = new ResourceOperationCode(ResourceConstants.CHANGE_ALERT_LEVEL, OP_CHANGE_ALERT_LEVEL);
+    public static final ResourceOperationCode CLOSE_DURABLE_CLIENT = new ResourceOperationCode(ResourceConstants.CLOSE_DURABLE_CLIENT, OP_CLOSE_DURABLE_CLIENT);
+    public static final ResourceOperationCode CLOSE_DURABLE_CQ = new ResourceOperationCode(ResourceConstants.CLOSE_DURABLE_CQ, OP_CLOSE_DURABLE_CQ);
+    public static final ResourceOperationCode COMPACT_DISKSTORE = new ResourceOperationCode(ResourceConstants.COMPACT_DISKSTORE, OP_COMPACT_DISKSTORE);
+    public static final ResourceOperationCode CONFIGURE_PDX = new ResourceOperationCode(ResourceConstants.CONFIGURE_PDX, OP_CONFIGURE_PDX);
+    public static final ResourceOperationCode CREATE_AEQ = new ResourceOperationCode(ResourceConstants.CREATE_AEQ, OP_CREATE_AEQ);
+    public static final ResourceOperationCode CREATE_DISKSTORE = new ResourceOperationCode(ResourceConstants.CREATE_DISKSTORE, OP_CREATE_DISKSTORE);
+    public static final ResourceOperationCode CREATE_GW_RECEIVER = new ResourceOperationCode(ResourceConstants.CREATE_GW_RECEIVER, OP_CREATE_GW_RECEIVER);
+    public static final ResourceOperationCode CREATE_GW_SENDER = new ResourceOperationCode(ResourceConstants.CREATE_GW_SENDER, OP_CREATE_GW_SENDER);
+    public static final ResourceOperationCode CREATE_INDEX = new ResourceOperationCode(ResourceConstants.CREATE_INDEX, OP_CREATE_INDEX);
+    public static final ResourceOperationCode CREATE_REGION = new ResourceOperationCode(ResourceConstants.CREATE_REGION, OP_CREATE_REGION);
+    public static final ResourceOperationCode DEPLOY = new ResourceOperationCode(ResourceConstants.DEPLOY, OP_DEPLOY);
+    public static final ResourceOperationCode DESTROY_DISKSTORE = new ResourceOperationCode(ResourceConstants.DESTROY_DISKSTORE, OP_DESTROY_DISKSTORE);
+    public static final ResourceOperationCode DESTROY_FUNCTION = new ResourceOperationCode(ResourceConstants.DESTROY_FUNCTION, OP_DESTROY_FUNCTION);
+    public static final ResourceOperationCode DESTROY_INDEX = new ResourceOperationCode(ResourceConstants.DESTROY_INDEX, OP_DESTROY_INDEX);
+    public static final ResourceOperationCode DESTROY_REGION = new ResourceOperationCode(ResourceConstants.DESTROY_REGION, OP_DESTROY_REGION);
+    public static final ResourceOperationCode EXECUTE_FUNCTION = new ResourceOperationCode(ResourceConstants.EXECUTE_FUNCTION, OP_EXECUTE_FUNCTION);
+    public static final ResourceOperationCode EXPORT_CONFIG = new ResourceOperationCode(ResourceConstants.EXPORT_CONFIG, OP_EXPORT_CONFIG);
+    public static final ResourceOperationCode EXPORT_DATA = new ResourceOperationCode(ResourceConstants.EXPORT_DATA, OP_EXPORT_DATA);
+    public static final ResourceOperationCode EXPORT_LOGS = new ResourceOperationCode(ResourceConstants.EXPORT_LOGS, OP_EXPORT_LOGS);
+    public static final ResourceOperationCode EXPORT_OFFLINE_DISKSTORE = new ResourceOperationCode(ResourceConstants.EXPORT_OFFLINE_DISKSTORE, OP_EXPORT_OFFLINE_DISKSTORE);
+    public static final ResourceOperationCode EXPORT_STACKTRACE = new ResourceOperationCode(ResourceConstants.EXPORT_STACKTRACE, OP_EXPORT_STACKTRACE);
+    public static final ResourceOperationCode GC = new ResourceOperationCode(ResourceConstants.GC, OP_GC);
+    public static final ResourceOperationCode GET = new ResourceOperationCode(ResourceConstants.GET, OP_GET);
+    public static final ResourceOperationCode IMPORT_CONFIG = new ResourceOperationCode(ResourceConstants.IMPORT_CONFIG, OP_IMPORT_CONFIG);
+    public static final ResourceOperationCode IMPORT_DATA = new ResourceOperationCode(ResourceConstants.IMPORT_DATA, OP_IMPORT_DATA);
+    public static final ResourceOperationCode LIST_DS = new ResourceOperationCode(ResourceConstants.LIST_DS, OP_LIST_DS);
+    public static final ResourceOperationCode LOAD_BALANCE_GW_SENDER = new ResourceOperationCode(ResourceConstants.LOAD_BALANCE_GW_SENDER, OP_LOAD_BALANCE_GW_SENDER);
+    public static final ResourceOperationCode LOCATE_ENTRY = new ResourceOperationCode(ResourceConstants.LOCATE_ENTRY, OP_LOCATE_ENTRY);
+    public static final ResourceOperationCode NETSTAT = new ResourceOperationCode(ResourceConstants.NETSTAT, OP_NETSTAT);
+    public static final ResourceOperationCode PAUSE_GW_SENDER = new ResourceOperationCode(ResourceConstants.PAUSE_GW_SENDER, OP_PAUSE_GW_SENDER);
+    public static final ResourceOperationCode PUT = new ResourceOperationCode(ResourceConstants.PUT, OP_PUT);
+    public static final ResourceOperationCode QUERY = new ResourceOperationCode(ResourceConstants.QUERY, OP_QUERY);
+    public static final ResourceOperationCode REBALANCE = new ResourceOperationCode(ResourceConstants.REBALANCE, OP_REBALANCE);
+    public static final ResourceOperationCode REMOVE = new ResourceOperationCode(ResourceConstants.REMOVE, OP_REMOVE);
+    public static final ResourceOperationCode RENAME_PDX = new ResourceOperationCode(ResourceConstants.RENAME_PDX, OP_RENAME_PDX);
+    public static final ResourceOperationCode RESUME_GW_SENDER = new ResourceOperationCode(ResourceConstants.RESUME_GW_SENDER, OP_RESUME_GW_SENDER);
+    public static final ResourceOperationCode REVOKE_MISSING_DISKSTORE = new ResourceOperationCode(ResourceConstants.REVOKE_MISSING_DISKSTORE, OP_REVOKE_MISSING_DISKSTORE);
+    public static final ResourceOperationCode SHOW_DEADLOCKS = new ResourceOperationCode(ResourceConstants.SHOW_DEADLOCKS, OP_SHOW_DEADLOCKS);
+    public static final ResourceOperationCode SHOW_LOG = new ResourceOperationCode(ResourceConstants.SHOW_LOG, OP_SHOW_LOG);
+    public static final ResourceOperationCode SHOW_METRICS = new ResourceOperationCode(ResourceConstants.SHOW_METRICS, OP_SHOW_METRICS);
+    public static final ResourceOperationCode SHOW_MISSING_DISKSTORES = new ResourceOperationCode(ResourceConstants.SHOW_MISSING_DISKSTORES, OP_SHOW_MISSING_DISKSTORES);
+    public static final ResourceOperationCode SHOW_SUBSCRIPTION_QUEUE_SIZE = new ResourceOperationCode(ResourceConstants.SHOW_SUBSCRIPTION_QUEUE_SIZE, OP_SHOW_SUBSCRIPTION_QUEUE_SIZE);
+    public static final ResourceOperationCode SHUTDOWN = new ResourceOperationCode(ResourceConstants.SHUTDOWN, OP_SHUTDOWN);
+    public static final ResourceOperationCode STOP_GW_RECEIVER = new ResourceOperationCode(ResourceConstants.STOP_GW_RECEIVER, OP_STOP_GW_RECEIVER);
+    public static final ResourceOperationCode STOP_GW_SENDER = new ResourceOperationCode(ResourceConstants.STOP_GW_SENDER, OP_STOP_GW_SENDER);
+    public static final ResourceOperationCode UNDEPLOY = new ResourceOperationCode(ResourceConstants.UNDEPLOY, OP_UNDEPLOY);
+    public static final ResourceOperationCode BACKUP_MEMBERS = new ResourceOperationCode(ResourceConstants.BACKUP_MEMBERS, OP_BACKUP_MEMBERS);
+    public static final ResourceOperationCode ROLL_DISKSTORE = new ResourceOperationCode(ResourceConstants.ROLL_DISKSTORE, OP_ROLL_DISKSTORE);
+    public static final ResourceOperationCode FORCE_COMPACTION = new ResourceOperationCode(ResourceConstants.FORCE_COMPACTION, OP_FORCE_COMPACTION);
+    public static final ResourceOperationCode FORCE_ROLL = new ResourceOperationCode(ResourceConstants.FORCE_ROLL, OP_FORCE_ROLL);
+    public static final ResourceOperationCode FLUSH_DISKSTORE = new ResourceOperationCode(ResourceConstants.FLUSH_DISKSTORE, OP_FLUSH_DISKSTORE);
+    public static final ResourceOperationCode START_GW_RECEIVER = new ResourceOperationCode(ResourceConstants.START_GW_RECEIVER, OP_START_GW_RECEIVER);
+    public static final ResourceOperationCode START_GW_SENDER = new ResourceOperationCode(ResourceConstants.START_GW_SENDER, OP_START_GW_SENDER);
+    public static final ResourceOperationCode BECOME_LOCK_GRANTOR = new ResourceOperationCode(ResourceConstants.BECOME_LOCK_GRANTOR, OP_BECOME_LOCK_GRANTOR);
+    public static final ResourceOperationCode START_MANAGER = new ResourceOperationCode(ResourceConstants.START_MANAGER, OP_START_MANAGER);
+    public static final ResourceOperationCode STOP_MANAGER = new ResourceOperationCode(ResourceConstants.STOP_MANAGER, OP_STOP_MANAGER);
+    public static final ResourceOperationCode CREATE_MANAGER = new ResourceOperationCode(ResourceConstants.CREATE_MANAGER, OP_CREATE_MANAGER);
+    public static final ResourceOperationCode STOP_CONTINUOUS_QUERY = new ResourceOperationCode(ResourceConstants.STOP_CONTINUOUS_QUERY, OP_STOP_CONTINUOUS_QUERY);
+    public static final ResourceOperationCode SET_DISK_USAGE = new ResourceOperationCode(ResourceConstants.SET_DISK_USAGE, OP_SET_DISK_USAGE);
+    public static final ResourceOperationCode CREATE_HDFS_STORE = new ResourceOperationCode(ResourceConstants.CREATE_HDFS_STORE, OP_CREATE_HDFS_STORE);
+    public static final ResourceOperationCode ALTER_HDFS_STORE = new ResourceOperationCode(ResourceConstants.ALTER_HDFS_STORE, OP_ALTER_HDFS_STORE);
+    public static final ResourceOperationCode DESTROY_HDFS_STORE = new ResourceOperationCode(ResourceConstants.DESTROY_HDFS_STORE, OP_DESTROY_HDFS_STORE);
+    
+
+    public static final ResourceOperationCode PULSE_DASHBOARD = new ResourceOperationCode(
+        ResourceConstants.PULSE_DASHBOARD, OP_PULSE_DASHBOARD);
+    public static final ResourceOperationCode PULSE_DATABROWSER = new ResourceOperationCode(
+        ResourceConstants.PULSE_DATABROWSER, OP_PULSE_DATABROWSER);
+    public static final ResourceOperationCode PULSE_WEBGFSH = new ResourceOperationCode(
+        ResourceConstants.PULSE_WEBGFSH, OP_PULSE_WEBGFSH);
+    public static final ResourceOperationCode PULSE_ADMIN_V1 = new ResourceOperationCode(
+        ResourceConstants.PULSE_ADMIN_V1, OP_PULSE_ADMIN_V1);
+      
+    public static final ResourceOperationCode DATA_READ = new ResourceOperationCode(ResourceConstants.DATA_READ, 
+        OP_DATA_READ,
+        new ResourceOperationCode[]{ 
+          LIST_DS, 
+          PULSE_DASHBOARD
+    });
+    
+    public static final ResourceOperationCode DATA_WRITE = new ResourceOperationCode(ResourceConstants.DATA_WRITE,
+        OP_DATA_WRITE,
+        new ResourceOperationCode[]{ 
+          DATA_READ, 
+          QUERY, 
+          BECOME_LOCK_GRANTOR, 
+          PUT, 
+          REMOVE, 
+          EXECUTE_FUNCTION, 
+          PULSE_DATABROWSER
+    });
+    
+    public static final ResourceOperationCode MONITOR = new ResourceOperationCode(ResourceConstants.MONITOR,
+        OP_MONITOR,
+        new ResourceOperationCode[] {
+          DATA_READ, 
+          EXPORT_CONFIG,
+          EXPORT_DATA,
+          EXPORT_LOGS,
+          EXPORT_OFFLINE_DISKSTORE,
+          EXPORT_STACKTRACE,
+          SHOW_DEADLOCKS,
+          SHOW_LOG,
+          SHOW_METRICS,
+          SHOW_MISSING_DISKSTORES,
+          SHOW_SUBSCRIPTION_QUEUE_SIZE       
+    });
+    
+    public static final ResourceOperationCode ADMIN = new ResourceOperationCode(ResourceConstants.ADMIN,
+        OP_ADMIN,
+        new ResourceOperationCode[] {
+          DATA_WRITE,
+          MONITOR,
+          ALTER_REGION,
+          ALTER_RUNTIME,
+          BACKUP_DISKSTORE,
+          CHANGE_ALERT_LEVEL,
+          CLOSE_DURABLE_CLIENT,
+          CLOSE_DURABLE_CQ,
+          COMPACT_DISKSTORE,
+          CONFIGURE_PDX,
+          CREATE_AEQ,
+          CREATE_DISKSTORE,
+          CREATE_GW_RECEIVER,
+          CREATE_GW_SENDER,
+          CREATE_INDEX,
+          CREATE_REGION,
+          DEPLOY,
+          DESTROY_DISKSTORE,
+          DESTROY_FUNCTION,
+          DESTROY_INDEX,
+          DESTROY_REGION,
+          GC,
+          GET,
+          IMPORT_CONFIG,
+          IMPORT_DATA,
+          LIST_DS,
+          LOAD_BALANCE_GW_SENDER,
+          LOCATE_ENTRY,
+          NETSTAT,
+          PAUSE_GW_SENDER,
+          REBALANCE,
+          RENAME_PDX,
+          RESUME_GW_SENDER,
+          REVOKE_MISSING_DISKSTORE,
+          SHUTDOWN,
+          STOP_GW_RECEIVER,
+          STOP_GW_SENDER,
+          UNDEPLOY,
+          BACKUP_MEMBERS,
+          ROLL_DISKSTORE,
+          FORCE_COMPACTION,
+          FORCE_ROLL,
+          FLUSH_DISKSTORE,
+          START_GW_RECEIVER,
+          START_GW_SENDER,
+          START_MANAGER,
+          STOP_MANAGER,
+          CREATE_MANAGER,
+          STOP_CONTINUOUS_QUERY,
+          SET_DISK_USAGE,
+          PULSE_WEBGFSH,
+          PULSE_ADMIN_V1
+    });
+    
+      
+    private final String name;
+    private final int opCode;
+    private final List<ResourceOperationCode> children;    
+
+    private ResourceOperationCode(String name, int opCode) {
+      this.name = name;
+      this.opCode = opCode;
+      VALUES[opCode] = this;
+      OperationNameMap.put(name, this);
+      this.children = null;
+    }
+
+    private ResourceOperationCode(String name, int opCode, ResourceOperationCode[] children) {
+      this.name = name;
+      this.opCode = opCode;
+      VALUES[opCode] = this;
+      OperationNameMap.put(name, this);      
+      this.children = new ArrayList<ResourceOperationCode>();
+      for(ResourceOperationCode code : children) {
+        this.children.add(code);
       }
+    }
+      
+    public List<ResourceOperationCode> getChildren() {
+      return Collections.unmodifiableList(children);
+    }
+    
+    public void addChild(ResourceOperationCode code) {
+      this.children.add(code);
+    }
+
+    /**
+     * Returns the <code>OperationCode</code> represented by specified int.
+     */
+    public static ResourceOperationCode fromOrdinal(int opCode) {
+      return VALUES[opCode];
+    }
+
+    /**
+     * Returns the <code>OperationCode</code> represented by specified string.
+     */
+    public static ResourceOperationCode parse(String operationName) {
+      return OperationNameMap.get(operationName);
+    }
+
+    /**
+     * Returns the int representing this operation code.
+     * 
+     * @return a int representing this operation.
+     */
+    public int toOrdinal() {
+      return this.opCode;
+    }
+
+    /**
+     * Returns a string representation for this operation.
+     * 
+     * @return the name of this operation.
+     */
+    @Override
+    final public String toString() {
+      return this.name;
+    }
+
+    /**
+     * Indicates whether other object is same as this one.
+     * 
+     * @return true if other object is same as this one.
+     */
+    @Override
+    final public boolean equals(final Object obj) {
+      if (obj == this) {
+        return true;
+      }
+      if (!(obj instanceof ResourceOperationCode)) {
+        return false;
+      }
+      final ResourceOperationCode other = (ResourceOperationCode) obj;
+      return (other.opCode == this.opCode);
+    }
+
+    /**
+     * Indicates whether other <code>OperationCode</code> is same as this one.
+     * 
+     * @return true if other <code>OperationCode</code> is same as this one.
+     */
+    final public boolean equals(final ResourceOperationCode opCode) {
+      return (opCode != null && opCode.opCode == this.opCode);
+    }
+
+    /**
+     * Returns a hash code value for this <code>OperationCode</code> which is
+     * the same as the int representing its operation type.
+     * 
+     * @return the hashCode of this operation.
+     */
+    @Override
+    final public int hashCode() {
+      return this.opCode;
+    }
+    
+    /**
+     * Returns true if passed operation is same or any one of its
+     * children
+     * 
+     * @param op
+     * @return true if  <code>OperationCode</code> matches 
+     */
+    public boolean allowedOp(ResourceOperationCode op) {
+      if(this.equals(op))
+        return true;
+      else {
+        if(children!=null) {
+          for(ResourceOperationCode child : children) {
+            if(child.allowedOp(op))
+              return true;
+          }
+        }
+      }
+      return false;
+    }
+  }
+
+  public abstract ResourceOperationCode getResourceOperationCode();
+   
+  @Override
+  public boolean isClientUpdate() {
+    return false;
+  }
+  
+  @Override
+  public boolean isPostOperation() {
+    return isPostOperation;
+  }
+
+  public void setPostOperationResult(Object result) {
+    this.isPostOperation = true;
+    this.opResult = result;
+  }
+  
+  public Object getOperationResult() {
+    return this.opResult;
+  }
 
-      /**
-	     * Returns the <code>OperationCode</code> represented by specified byte.
-	     */
-	    public static ResourceOperationCode fromOrdinal(byte opCode) {
-	      return VALUES[opCode];
-	    }
-
-	    /**
-	     * Returns the <code>OperationCode</code> represented by specified string.
-	     */
-	    public static ResourceOperationCode parse(String operationName) {
-	      return (ResourceOperationCode)OperationNameMap.get(operationName);
-	    }
-
-	    /**
-	     * Returns the byte representing this operation code.
-	     * 
-	     * @return a byte representing this operation.
-	     */
-	    public byte toOrdinal() {
-	      return this.opCode;
-	    }
-
-	    /**
-	     * Returns a string representation for this operation.
-	     * 
-	     * @return the name of this operation.
-	     */
-	    @Override
-	    final public String toString() {
-	      return this.name;
-	    }
-
-	    /**
-	     * Indicates whether other object is same as this one.
-	     * 
-	     * @return true if other object is same as this one.
-	     */
-	    @Override
-	    final public boolean equals(final Object obj) {
-	      if (obj == this) {
-	        return true;
-	      }
-	      if (!(obj instanceof ResourceOperationCode)) {
-	        return false;
-	      }
-	      final ResourceOperationCode other = (ResourceOperationCode)obj;
-	      return (other.opCode == this.opCode);
-	    }
-
-	    /**
-	     * Indicates whether other <code>OperationCode</code> is same as this one.
-	     * 
-	     * @return true if other <code>OperationCode</code> is same as this one.
-	     */
-	    final public boolean equals(final ResourceOperationCode opCode) {
-	      return (opCode != null && opCode.opCode == this.opCode);
-	    }
-
-	    /**
-	     * Returns a hash code value for this <code>OperationCode</code> which is
-	     * the same as the byte representing its operation type.
-	     * 
-	     * @return the hashCode of this operation.
-	     */
-	    @Override
-	    final public int hashCode() {
-	      return this.opCode;
-	    }
-
-	    
-	 }
-	
-
-	 public abstract ResourceOperationCode getResourceOperationCode();
-	 
-	 /*
-	@Override
-	public OperationCode getOperationCode() {
-		// TODO Auto-generated method stub
-		return null;
-	}*/
-
-	@Override
-	public boolean isPostOperation() {
-		return false;
-	}
-
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/SetAttributesOperationContext.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/SetAttributesOperationContext.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/SetAttributesOperationContext.java
new file mode 100644
index 0000000..33f4ad9
--- /dev/null
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/SetAttributesOperationContext.java
@@ -0,0 +1,39 @@
+package com.gemstone.gemfire.management.internal.security;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Used to encapsulate Context passed AccessControl Plugin for each of the
+ * attributes in attribute list passed to setAttributes call on given MBean  
+ * 
+ * @author tushark
+ * @since 9.0
+ */
+public class SetAttributesOperationContext extends ResourceOperationContext {
+  
+  private Map<String,ResourceOperationContext> contextMap = null;
+  
+  public SetAttributesOperationContext(){
+    contextMap = new HashMap<String,ResourceOperationContext>();
+  }
+  
+  public void addAttribute(String attr, ResourceOperationContext setterContext) {
+    this.contextMap.put(attr, setterContext);
+  }
+  
+  public Map<String,ResourceOperationContext> getAttributesContextMap(){
+    return contextMap;
+  }
+
+  @Override
+  public ResourceOperationCode getResourceOperationCode() {    
+    return null;
+  }
+
+  @Override
+  public OperationCode getOperationCode() {    
+    return null;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/AbstractCommandsController.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/AbstractCommandsController.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/AbstractCommandsController.java
index 73ce926..0aa614f 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/AbstractCommandsController.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/AbstractCommandsController.java
@@ -8,35 +8,53 @@
 
 package com.gemstone.gemfire.management.internal.web.controllers;
 
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.ACCESS_DENIED_MESSAGE;
+
 import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.lang.management.ManagementFactory;
 import java.net.URI;
+import java.security.Principal;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
+import java.util.Properties;
 import java.util.Set;
+
 import javax.management.JMX;
 import javax.management.MBeanServer;
 import javax.management.MalformedObjectNameException;
 import javax.management.ObjectName;
 import javax.management.Query;
 import javax.management.QueryExp;
+import javax.management.remote.JMXPrincipal;
+import javax.security.auth.Subject;
 
+import com.gemstone.gemfire.GemFireConfigException;
+import com.gemstone.gemfire.cache.CacheFactory;
+import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
 import com.gemstone.gemfire.internal.lang.StringUtils;
 import com.gemstone.gemfire.internal.logging.LogService;
 import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
 import com.gemstone.gemfire.internal.util.ArrayUtils;
 import com.gemstone.gemfire.management.DistributedSystemMXBean;
+import com.gemstone.gemfire.management.ManagementService;
 import com.gemstone.gemfire.management.MemberMXBean;
 import com.gemstone.gemfire.management.internal.MBeanJMXAdapter;
 import com.gemstone.gemfire.management.internal.ManagementConstants;
+import com.gemstone.gemfire.management.internal.SystemManagementService;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
 import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import com.gemstone.gemfire.management.internal.security.CLIOperationContext;
+import com.gemstone.gemfire.management.internal.security.MBeanServerWrapper;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperationContext;
 import com.gemstone.gemfire.management.internal.web.controllers.support.EnvironmentVariablesHandlerInterceptor;
 import com.gemstone.gemfire.management.internal.web.controllers.support.MemberMXBeanAdapter;
 import com.gemstone.gemfire.management.internal.web.util.UriUtils;
+import com.gemstone.gemfire.security.AccessControl;
+import com.gemstone.gemfire.security.Authenticator;
 
 import org.apache.logging.log4j.Logger;
 import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
@@ -46,6 +64,7 @@ import org.springframework.web.bind.WebDataBinder;
 import org.springframework.web.bind.annotation.ExceptionHandler;
 import org.springframework.web.bind.annotation.InitBinder;
 import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.ResponseStatus;
 import org.springframework.web.context.request.WebRequest;
 import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
 
@@ -71,6 +90,27 @@ public abstract class AbstractCommandsController {
   protected static final String REST_API_VERSION = "/v1";
 
   private MemberMXBean managingMemberMXBeanProxy;
+  
+
+  
+  private Class accessControlKlass;
+  
+  private GemFireCacheImpl cache;
+  
+  // Convert a predefined exception to an HTTP Status code
+  @ResponseStatus(value=HttpStatus.UNAUTHORIZED, reason="Not authenticated")  // 401
+  @ExceptionHandler(com.gemstone.gemfire.security.AuthenticationFailedException.class)
+  public void authenticate() {
+    
+  }
+  
+  // Convert a predefined exception to an HTTP Status code
+  @ResponseStatus(value=HttpStatus.FORBIDDEN, reason="Access Denied")  // 403
+  @ExceptionHandler(java.lang.SecurityException.class)
+  public void authorize() {
+   
+  }
+  
 
   /**
    * Asserts the argument is valid, as determined by the caller passing the result of an evaluated expression to this
@@ -401,8 +441,8 @@ public abstract class AbstractCommandsController {
       final DistributedSystemMXBean distributedSystemMXBean = JMX.newMXBeanProxy(platformMBeanServer,
         MBeanJMXAdapter.getDistributedSystemName(), DistributedSystemMXBean.class);
 
-      //managingMemberMXBeanProxy = createMemberMXBeanForManagerUsingAdapter(platformMBeanServer,
-      //  distributedSystemMXBean.getMemberObjectName());
+      /*managingMemberMXBeanProxy = createMemberMXBeanForManagerUsingAdapter(platformMBeanServer,
+      distributedSystemMXBean.getMemberObjectName());*/
 
       managingMemberMXBeanProxy = createMemberMXBeanForManagerUsingProxy(platformMBeanServer,
         distributedSystemMXBean.getMemberObjectName());
@@ -410,6 +450,15 @@ public abstract class AbstractCommandsController {
 
     return managingMemberMXBeanProxy;
   }
+  
+  protected synchronized ObjectName getMemberObjectName() {
+    final MBeanServer platformMBeanServer = getMBeanServer();
+
+    final DistributedSystemMXBean distributedSystemMXBean = JMX.newMXBeanProxy(platformMBeanServer,
+        MBeanJMXAdapter.getDistributedSystemName(), DistributedSystemMXBean.class);
+
+    return distributedSystemMXBean.getMemberObjectName();
+  }
 
   /**
    * Creates an Adapter using the Platform MBeanServer and ObjectName to invoke operations on the GemFire Manager's
@@ -449,7 +498,6 @@ public abstract class AbstractCommandsController {
    */
   protected Map<String, String> getEnvironment() {
     final Map<String, String> environment = new HashMap<String, String>();
-
     environment.putAll(EnvironmentVariablesHandlerInterceptor.getEnvironment());
     environment.put(Gfsh.ENV_APP_NAME, Gfsh.GFSH_APP_NAME);
 
@@ -505,6 +553,13 @@ public abstract class AbstractCommandsController {
   protected String processCommand(final String command) {
     return processCommand(command, getEnvironment(), null);
   }
+  
+  protected String processCommandWithCredentials(final String command, Properties credentials) {
+    if (credentials != null) {
+      EnvironmentVariablesHandlerInterceptor.CREDENTIALS.set(credentials);
+    }
+    return processCommand(command, getEnvironment(), null);
+  }
 
   /**
    * Executes the specified command as entered by the user using the GemFire Shell (Gfsh).  Note, Gfsh performs
@@ -522,6 +577,13 @@ public abstract class AbstractCommandsController {
   protected String processCommand(final String command, final byte[][] fileData) {
     return processCommand(command, getEnvironment(), fileData);
   }
+  
+  protected String processCommandWithCredentials(final String command, final byte[][] fileData, Properties credentials) {
+    if (credentials != null) {
+      EnvironmentVariablesHandlerInterceptor.CREDENTIALS.set(credentials);
+    }
+    return processCommand(command, getEnvironment(), fileData);
+  }
 
   /**
    * Executes the specified command as entered by the user using the GemFire Shell (Gfsh).  Note, Gfsh performs
@@ -556,11 +618,42 @@ public abstract class AbstractCommandsController {
    * @see com.gemstone.gemfire.management.MemberMXBean#processCommand(String, java.util.Map, Byte[][])
    */
   protected String processCommand(final String command, final Map<String, String> environment, final byte[][] fileData) {
-    logger.info(LogMarker.CONFIG, "Processing Command ({}) with Environment ({}) having File Data ({})...",
-        command, environment, (fileData != null));
+    logger.info(LogMarker.CONFIG, "Processing Command ({}) with Environment ({}) having File Data ({})...", command,
+        environment, (fileData != null));
+
+    ResourceOperationContext ctx = authorize(command);
+
+    String result =  getManagingMemberMXBean().processCommand(command, environment, ArrayUtils.toByteArray(fileData));
+    
+    ctx = postAuthorize(command, ctx, result);
+    
+    return result;
+  }
+
+  protected ResourceOperationContext authorize(final String command) {
+
     
-    return getManagingMemberMXBean().processCommand(command, environment, ArrayUtils.toByteArray(fileData));
+    SystemManagementService service = (SystemManagementService) ManagementService
+        .getExistingManagementService(CacheFactory.getAnyInstance());
+    Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    CLIOperationContext context = new CLIOperationContext(command);
+    service.getAuthManager().authorize(credentials, context);
+    return context;
+  }
+  
+  protected ResourceOperationContext postAuthorize(final String command, ResourceOperationContext context, Object result) {
+
+    context.setPostOperationResult(result);
+    SystemManagementService service = (SystemManagementService) ManagementService
+        .getExistingManagementService(CacheFactory.getAnyInstance());
+    Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+
+    service.getAuthManager().postAuthorize(credentials, context);
+    return context;
   }
+  
+  
+
 
   /**
    * The MemberMXBeanProxy class is a proxy for the MemberMXBean interface transforming an operation on the member

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/ConfigCommandsController.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/ConfigCommandsController.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/ConfigCommandsController.java
index 517d942..04197c5 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/ConfigCommandsController.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/ConfigCommandsController.java
@@ -8,11 +8,13 @@
 package com.gemstone.gemfire.management.internal.web.controllers;
 
 import java.io.IOException;
+import java.util.Properties;
 import java.util.concurrent.Callable;
 
 import com.gemstone.gemfire.internal.lang.StringUtils;
 import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import com.gemstone.gemfire.management.internal.web.controllers.support.EnvironmentVariablesHandlerInterceptor;
 import com.gemstone.gemfire.management.internal.web.util.ConvertUtils;
 
 import org.springframework.http.HttpStatus;
@@ -160,9 +162,11 @@ public class ConfigCommandsController extends AbstractMultiPartCommandsControlle
       command.addOption(CliStrings.EXPORT_CONFIG__DIR, decode(directory));
     }
 
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }
@@ -179,9 +183,11 @@ public class ConfigCommandsController extends AbstractMultiPartCommandsControlle
       command.addOption(CliStrings.EXPORT_SHARED_CONFIG__DIR, directory);
     }
 
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }
@@ -195,9 +201,11 @@ public class ConfigCommandsController extends AbstractMultiPartCommandsControlle
 
     command.addOption(CliStrings.IMPORT_SHARED_CONFIG__ZIP, zipFileName);
 
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString(), ConvertUtils.convert(zipFileResources)), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), ConvertUtils.convert(zipFileResources), credentials), HttpStatus.OK);
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DataCommandsController.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DataCommandsController.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DataCommandsController.java
index 6767ec1..d11a380 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DataCommandsController.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DataCommandsController.java
@@ -7,11 +7,13 @@
  */
 package com.gemstone.gemfire.management.internal.web.controllers;
 
+import java.util.Properties;
 import java.util.concurrent.Callable;
 
 import com.gemstone.gemfire.internal.lang.StringUtils;
 import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import com.gemstone.gemfire.management.internal.web.controllers.support.EnvironmentVariablesHandlerInterceptor;
 
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
@@ -129,9 +131,11 @@ public class DataCommandsController extends AbstractCommandsController {
     command.addOption(CliStrings.EXPORT_DATA__REGION, decode(regionNamePath));
     command.addOption(CliStrings.EXPORT_DATA__FILE, decode(file));
 
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }
@@ -147,9 +151,11 @@ public class DataCommandsController extends AbstractCommandsController {
     command.addOption(CliStrings.IMPORT_DATA__REGION, decode(regionNamePath));
     command.addOption(CliStrings.IMPORT_DATA__FILE, decode(file));
 
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }
@@ -194,9 +200,11 @@ public class DataCommandsController extends AbstractCommandsController {
     command.addOption(CliStrings.QUERY__STEPNAME, stepName);
     command.addOption(CliStrings.QUERY__INTERACTIVE, String.valueOf(Boolean.TRUE.equals(interactive)));
 
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }
@@ -222,9 +230,11 @@ public class DataCommandsController extends AbstractCommandsController {
     command.addOption(CliStrings.REBALANCE__SIMULATE, String.valueOf(simulate));
     command.addOption(CliStrings.REBALANCE__TIMEOUT, String.valueOf(timeout));
 
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DiskStoreCommandsController.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DiskStoreCommandsController.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DiskStoreCommandsController.java
index 2df3432..3cbffe4 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DiskStoreCommandsController.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/DiskStoreCommandsController.java
@@ -7,11 +7,14 @@
  */
 package com.gemstone.gemfire.management.internal.web.controllers;
 
+import java.util.Properties;
 import java.util.concurrent.Callable;
 
 import com.gemstone.gemfire.internal.lang.StringUtils;
 import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import com.gemstone.gemfire.management.internal.security.CLIOperationContext;
+import com.gemstone.gemfire.management.internal.web.controllers.support.EnvironmentVariablesHandlerInterceptor;
 
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
@@ -60,9 +63,11 @@ public class DiskStoreCommandsController extends AbstractCommandsController {
       command.addOption(CliStrings.BACKUP_DISK_STORE__BASELINEDIR, decode(baselineDir));
     }
 
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }
@@ -79,9 +84,11 @@ public class DiskStoreCommandsController extends AbstractCommandsController {
       command.addOption(CliStrings.COMPACT_DISK_STORE__GROUP, StringUtils.concat(groups, StringUtils.COMMA_DELIMITER));
     }
 
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/FunctionCommandsController.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/FunctionCommandsController.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/FunctionCommandsController.java
index de81543..3001778 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/FunctionCommandsController.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/FunctionCommandsController.java
@@ -7,11 +7,13 @@
  */
 package com.gemstone.gemfire.management.internal.web.controllers;
 
+import java.util.Properties;
 import java.util.concurrent.Callable;
 
 import com.gemstone.gemfire.internal.lang.StringUtils;
 import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import com.gemstone.gemfire.management.internal.web.controllers.support.EnvironmentVariablesHandlerInterceptor;
 
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
@@ -102,9 +104,12 @@ public class FunctionCommandsController extends AbstractCommandsController {
       command.addOption(CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR, resultCollector);
     }
 
+    
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/MiscellaneousCommandsController.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/MiscellaneousCommandsController.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/MiscellaneousCommandsController.java
index 66d344f..67c4b11 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/MiscellaneousCommandsController.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/MiscellaneousCommandsController.java
@@ -7,11 +7,13 @@
  */
 package com.gemstone.gemfire.management.internal.web.controllers;
 
+import java.util.Properties;
 import java.util.concurrent.Callable;
 
 import com.gemstone.gemfire.internal.lang.StringUtils;
 import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import com.gemstone.gemfire.management.internal.web.controllers.support.EnvironmentVariablesHandlerInterceptor;
 
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
@@ -78,10 +80,12 @@ public class MiscellaneousCommandsController extends AbstractCommandsController
     if (hasValue(endTime)) {
       command.addOption(CliStrings.EXPORT_LOGS__ENDTIME, endTime);
     }
-
+    
+    final Properties credentials = EnvironmentVariablesHandlerInterceptor.CREDENTIALS.get();
+    
     return new Callable<ResponseEntity<String>>() {
       @Override public ResponseEntity<String> call() throws Exception {
-        return new ResponseEntity<String>(processCommand(command.toString()), HttpStatus.OK);
+        return new ResponseEntity<String>(processCommandWithCredentials(command.toString(), credentials), HttpStatus.OK);
       }
     };
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java
index 97f9bbe..6e2bb40 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java
@@ -257,7 +257,7 @@ public class WanCommandsController extends AbstractCommandsController {
                                     @RequestParam(value = CliStrings.RESUME_GATEWAYSENDER__GROUP, required = false) final String[] groups,
                                     @RequestParam(value = CliStrings.RESUME_GATEWAYSENDER__MEMBER, required = false) final String[] members)
   {
-    CommandStringBuilder command = new CommandStringBuilder(CliStrings.RESUME_GATEWAYSENDER__ID);
+    CommandStringBuilder command = new CommandStringBuilder(CliStrings.RESUME_GATEWAYSENDER);
 
     command.addOption(CliStrings.RESUME_GATEWAYSENDER__ID, decode(gatewaySenderId));
 

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java.rej
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java.rej b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java.rej
new file mode 100644
index 0000000..f8ce82a
--- /dev/null
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java.rej
@@ -0,0 +1,10 @@
+diff a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/WanCommandsController.java	(rejected hunks)
+@@ -298,7 +298,7 @@ public class WanCommandsController extends AbstractCommandsController {
+                                    @RequestParam(value = CliStrings.START_GATEWAYSENDER__GROUP, required = false) final String[] groups,
+                                    @RequestParam(value = CliStrings.START_GATEWAYSENDER__MEMBER, required = false) final String[] members)
+   {
+-    CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_GATEWAYRECEIVER);
++    CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_GATEWAYSENDER);
+ 
+     command.addOption(CliStrings.START_GATEWAYSENDER__ID, gatewaySenderId);
+ 

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/support/EnvironmentVariablesHandlerInterceptor.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/support/EnvironmentVariablesHandlerInterceptor.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/support/EnvironmentVariablesHandlerInterceptor.java
index 8ebed02..47a58d7 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/support/EnvironmentVariablesHandlerInterceptor.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/controllers/support/EnvironmentVariablesHandlerInterceptor.java
@@ -7,15 +7,47 @@
  */
 package com.gemstone.gemfire.management.internal.web.controllers.support;
 
+import java.lang.reflect.Method;
+import java.security.Principal;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.Map.Entry;
+
+import javax.management.remote.JMXPrincipal;
+import javax.security.auth.Subject;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
+import com.gemstone.gemfire.GemFireConfigException;
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.CacheFactory;
+import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.distributed.DistributedSystem;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.ClassLoadUtil;
+import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.logging.InternalLogWriter;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.management.ManagementService;
+import com.gemstone.gemfire.management.internal.SystemManagementService;
+import com.gemstone.gemfire.management.internal.security.CLIOperationContext;
+import com.gemstone.gemfire.management.internal.security.MBeanServerWrapper;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.security.AccessControl;
+import com.gemstone.gemfire.security.AuthenticationFailedException;
+import com.gemstone.gemfire.security.AuthenticationRequiredException;
+import com.gemstone.gemfire.security.Authenticator;
+
+import org.apache.logging.log4j.Logger;
+
 /**
  * The GetEnvironmentHandlerInterceptor class handles extracting Gfsh environment variables encoded in the HTTP request
  * message as request parameters.
@@ -29,6 +61,16 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 @SuppressWarnings("unused")
 public class EnvironmentVariablesHandlerInterceptor extends HandlerInterceptorAdapter {
 
+  private static final Logger logger = LogService.getLogger();
+  
+  private Cache cache;
+  
+  private Authenticator auth = null;
+  
+  
+  public static final ThreadLocal<Properties> CREDENTIALS = new ThreadLocal<Properties>();
+  
+   
   private static final ThreadLocal<Map<String, String>> ENV = new ThreadLocal<Map<String, String>>() {
     @Override
     protected Map<String, String> initialValue() {
@@ -37,6 +79,8 @@ public class EnvironmentVariablesHandlerInterceptor extends HandlerInterceptorAd
   };
 
   protected static final String ENVIRONMENT_VARIABLE_REQUEST_PARAMETER_PREFIX = "vf.gf.env.";
+  
+  protected static final String SECURITY_VARIABLE_REQUEST_HEADER_PREFIX = "security-";
 
   public static Map<String, String> getEnvironment() {
     return ENV.get();
@@ -46,6 +90,7 @@ public class EnvironmentVariablesHandlerInterceptor extends HandlerInterceptorAd
   public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
     throws Exception
   {
+    
     final Map<String, String> requestParameterValues = new HashMap<String, String>();
 
     for (Enumeration<String> requestParameters = request.getParameterNames(); requestParameters.hasMoreElements(); ) {
@@ -56,11 +101,52 @@ public class EnvironmentVariablesHandlerInterceptor extends HandlerInterceptorAd
           request.getParameter(requestParameter));
       }
     }
+    
+ 
+    
+    for (Enumeration<String> requestHeaders = request.getHeaderNames(); requestHeaders.hasMoreElements();) {
 
+      final String requestHeader = requestHeaders.nextElement();
+
+      if (requestHeader.startsWith(SECURITY_VARIABLE_REQUEST_HEADER_PREFIX)) {
+        requestParameterValues.put(requestHeader, request.getHeader(requestHeader));
+      }
+
+    }
+    
+    securityCheck(requestParameterValues);
+    
     ENV.set(requestParameterValues);
 
     return true;
   }
+  
+
+  
+  protected void securityCheck(final Map<String, String> environment) {
+
+    Properties credentials = new Properties();
+
+    Iterator<Entry<String, String>> it = environment.entrySet().iterator();
+    while (it.hasNext()) {
+      Entry<String, String> entry = it.next();
+      if (entry.getKey().startsWith(SECURITY_VARIABLE_REQUEST_HEADER_PREFIX)) {
+        credentials.put(entry.getKey(), entry.getValue());
+      }
+
+    }
+    GemFireCacheImpl instance = GemFireCacheImpl.getInstance();
+    if(instance != null){
+      SystemManagementService service = (SystemManagementService) ManagementService
+          .getExistingManagementService(instance);
+      service.getAuthManager().verifyCredentials(credentials);
+      CREDENTIALS.set(credentials);
+    }
+
+
+  }
+
+  
 
   @Override
   public void afterCompletion(final HttpServletRequest request,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/http/support/SimpleHttpRequester.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/http/support/SimpleHttpRequester.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/http/support/SimpleHttpRequester.java
index 8bd9d37..7a83271 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/http/support/SimpleHttpRequester.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/http/support/SimpleHttpRequester.java
@@ -7,13 +7,33 @@
  */
 package com.gemstone.gemfire.management.internal.web.http.support;
 
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.URI;
+import java.util.Map;
+import java.util.Properties;
 import java.util.Set;
 
+import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.client.ClientHttpRequest;
+import org.springframework.http.client.ClientHttpResponse;
 import org.springframework.http.client.SimpleClientHttpRequestFactory;
+import org.springframework.web.client.RequestCallback;
+import org.springframework.web.client.ResponseErrorHandler;
+import org.springframework.web.client.RestClientException;
 import org.springframework.web.client.RestTemplate;
 
+import com.gemstone.gemfire.internal.lang.StringUtils;
+import com.gemstone.gemfire.internal.util.IOUtils;
+import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+
+
 /**
  * The SimpleHttpRequester class is a Adapter/facade for the Spring RestTemplate class for abstracting HTTP requests
  * and operations.
@@ -29,13 +49,18 @@ public class SimpleHttpRequester {
   protected static final int DEFAULT_CONNECT_TIMEOUT = (30 * 1000); // 30 seconds
 
   private final RestTemplate restTemplate;
+  
+  private String user;
+  
+  private String pwd;
 
+  private Map<String,String> securityProperties;
   /**
    * Default constructor to create an instance of the SimpleHttpRequester class using the default connection timeout
    * of 30 seconds.
    */
-  public SimpleHttpRequester() {
-    this(DEFAULT_CONNECT_TIMEOUT);
+  public SimpleHttpRequester(Gfsh gfsh,Map<String,String> securityProperties) {
+    this(gfsh, DEFAULT_CONNECT_TIMEOUT, securityProperties);
   }
 
   /**
@@ -44,12 +69,54 @@ public class SimpleHttpRequester {
    * @param connectTimeout an integer value specifying the timeout value in milliseconds for establishing the HTTP
    * connection to the HTTP server.
    */
-  public SimpleHttpRequester(final int connectTimeout) {
+  public SimpleHttpRequester(final Gfsh gfsh, final int connectTimeout, Map<String,String> securityProperties) {
     final SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
 
     clientHttpRequestFactory.setConnectTimeout(connectTimeout);
 
+    this.securityProperties = securityProperties;
     this.restTemplate = new RestTemplate(clientHttpRequestFactory);
+
+    this.restTemplate.setErrorHandler(new ResponseErrorHandler() {
+      @Override
+      public boolean hasError(final ClientHttpResponse response) throws IOException {
+        final HttpStatus status = response.getStatusCode();
+
+        switch (status) {
+        case BAD_REQUEST: // 400 *
+        case UNAUTHORIZED: // 401
+        case FORBIDDEN: // 403
+        case NOT_FOUND: // 404 *
+        case METHOD_NOT_ALLOWED: // 405 *
+        case NOT_ACCEPTABLE: // 406 *
+        case REQUEST_TIMEOUT: // 408
+        case CONFLICT: // 409
+        case REQUEST_ENTITY_TOO_LARGE: // 413
+        case REQUEST_URI_TOO_LONG: // 414
+        case UNSUPPORTED_MEDIA_TYPE: // 415 *
+        case TOO_MANY_REQUESTS: // 429
+        case INTERNAL_SERVER_ERROR: // 500 *
+        case NOT_IMPLEMENTED: // 501
+        case BAD_GATEWAY: // 502 ?
+        case SERVICE_UNAVAILABLE: // 503
+          return true;
+        default:
+          return false;
+        }
+      }
+
+      @Override
+      public void handleError(final ClientHttpResponse response) throws IOException {
+        final String message = String.format("The HTTP request failed with: %1$d - %2$s", response.getRawStatusCode(),
+            response.getStatusText());
+        
+        throw new RuntimeException(message);
+
+      }
+
+     
+    });
+
   }
 
   /**
@@ -118,7 +185,7 @@ public class SimpleHttpRequester {
   }
 
   /**
-   * Performs an HTTP PUT operation on the requested resource identified/located by the specified URL.
+   * Performs an HTTP PUT operation on the requested resource identifiedR/located by the specified URL.
    * <p/>
    * @param url a String value identifying or locating the resource intended for the HTTP operation.
    * @param urlVariables an array of variables to substitute in the URI/URL template.
@@ -127,5 +194,35 @@ public class SimpleHttpRequester {
   public void put(final String url, final Object requestBody, final Object... urlVariables) {
     getRestTemplate().put(url, requestBody, urlVariables);
   }
+  
+  /**
+   * Performs an HTTP GET operation on the requested resource identified/located
+   * by the specified URL.
+   * <p/>
+   * 
+   * @param url
+   *          a String value identifying or locating the resource intended for
+   *          the HTTP operation.
+   * @param urlVariables
+   *          an array of variables to substitute in the URI/URL template.
+   * @see org.springframework.web.client.RestTemplate#getForObject(String,
+   *      Class, Object...)
+   */
+  public <T> T exchange(final String url, final Class<T> responseType, final Object... urlVariables) {
+    ResponseEntity<T> response = getRestTemplate().exchange(url, HttpMethod.GET, getRequestEntity(), responseType);
+    return response.getBody();
+  }
+
+  protected HttpEntity<?> getRequestEntity() {
+    HttpHeaders requestHeaders = new HttpHeaders();  
+    if(this.securityProperties != null){
+      requestHeaders.setAll(securityProperties);
+    }
+
+    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
+
+    return requestEntity;
+
+  }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/AbstractHttpOperationInvoker.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/AbstractHttpOperationInvoker.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/AbstractHttpOperationInvoker.java
index dac1271..d84f744 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/AbstractHttpOperationInvoker.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/AbstractHttpOperationInvoker.java
@@ -14,12 +14,15 @@ import java.io.InputStreamReader;
 import java.net.URI;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
+
 import javax.management.ObjectName;
 import javax.management.QueryExp;
 
@@ -31,6 +34,7 @@ import com.gemstone.gemfire.management.DistributedSystemMXBean;
 import com.gemstone.gemfire.management.internal.MBeanJMXAdapter;
 import com.gemstone.gemfire.management.internal.ManagementConstants;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
 import com.gemstone.gemfire.management.internal.web.domain.Link;
 import com.gemstone.gemfire.management.internal.web.domain.QueryParameterSource;
 import com.gemstone.gemfire.management.internal.web.http.ClientHttpRequest;
@@ -105,6 +109,9 @@ public abstract class AbstractHttpOperationInvoker implements HttpOperationInvok
 
   // the base URL of the GemFire Manager's embedded HTTP service and REST API interface
   private final String baseUrl;
+  
+  
+  protected Map<String,String> securityProperties;
 
   /**
    * Default, public, no-arg constructor to create an instance of the AbstractHttpOperationInvoker class 
@@ -124,11 +131,11 @@ public abstract class AbstractHttpOperationInvoker implements HttpOperationInvok
    * @param gfsh a reference to the instance of the GemFire shell (Gfsh) using this HTTP-based OperationInvoker for
    * command processing.
    * @throws AssertionError if the reference to the Gfsh instance is null.
-   * @see #AbstractHttpOperationInvoker(com.gemstone.gemfire.management.internal.cli.shell.Gfsh, String)
+   * @see #AbstractHttpOperationInvoker(com.gemstone.gemfire.management.internal.cli.shell.Gfsh, String, Map)
    * @see com.gemstone.gemfire.management.internal.cli.shell.Gfsh
    */
-  public AbstractHttpOperationInvoker(final Gfsh gfsh) {
-    this(gfsh, REST_API_URL);
+  public AbstractHttpOperationInvoker(final Gfsh gfsh, Map<String,String> securityProperties) {
+    this(gfsh, REST_API_URL, securityProperties);
   }
 
   /**
@@ -143,12 +150,13 @@ public abstract class AbstractHttpOperationInvoker implements HttpOperationInvok
    * @throws AssertionError if the reference to the Gfsh instance is null.
    * @see com.gemstone.gemfire.management.internal.cli.shell.Gfsh
    */
-  public AbstractHttpOperationInvoker(final Gfsh gfsh, final String baseUrl) {
+  public AbstractHttpOperationInvoker(final Gfsh gfsh, final String baseUrl, Map<String,String> securityProperties) {
     assertNotNull(gfsh, "The reference to the GemFire shell (Gfsh) cannot be null!");
 
     this.gfsh = gfsh;
     this.baseUrl = StringUtils.defaultIfBlank(baseUrl, REST_API_URL);
-
+    this.securityProperties = securityProperties;
+  
     // constructs an instance of a single-threaded, scheduled Executor to send periodic HTTP requests to the Manager's
     // HTTP service or Web Service to assess the "alive" state
     this.executorService = Executors.newSingleThreadScheduledExecutor();
@@ -194,11 +202,12 @@ public abstract class AbstractHttpOperationInvoker implements HttpOperationInvok
         final String message = String.format("The HTTP request failed with: %1$d - %2$s", response.getRawStatusCode(),
           response.getStatusText());
 
-        gfsh.logSevere(message, null);
+        //gfsh.logSevere(message, null);
 
         if (gfsh.getDebug()) {
           gfsh.logSevere(readBody(response), null);
         }
+        throw new RuntimeException(message);
       }
 
       private String readBody(final ClientHttpResponse response) throws IOException {
@@ -350,6 +359,14 @@ public abstract class AbstractHttpOperationInvoker implements HttpOperationInvok
     final ClientHttpRequest request = new ClientHttpRequest(link);
     request.addHeaderValues(HttpHeader.USER_AGENT.getName(), USER_AGENT_HTTP_REQUEST_HEADER_VALUE);
     request.getHeaders().setAccept(getAcceptableMediaTypes());
+    
+    if(this.securityProperties != null){
+      Iterator<Entry<String, String>> it = this.securityProperties.entrySet().iterator();
+      while(it.hasNext()){
+        Entry<String,String> entry= it.next();
+        request.addHeaderValues(entry.getKey(), entry.getValue());
+      }
+    }
     return request;
   }
 
@@ -551,6 +568,8 @@ public abstract class AbstractHttpOperationInvoker implements HttpOperationInvok
       printInfo("HTTP response headers: %1$s", response.getHeaders());
       printInfo("HTTP response status: %1$d - %2$s", response.getStatusCode().value(),
         response.getStatusCode().getReasonPhrase());
+      
+      printInfo("HTTP response body: ", response.getBody());
     }
 
     return response;
@@ -788,5 +807,5 @@ public abstract class AbstractHttpOperationInvoker implements HttpOperationInvok
   public String toString() {
     return String.format("GemFire Manager HTTP service @ %1$s", getBaseUrl());
   }
-
+  
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/RestHttpOperationInvoker.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/RestHttpOperationInvoker.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/RestHttpOperationInvoker.java
index 0dfbdbd..320214d 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/RestHttpOperationInvoker.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/RestHttpOperationInvoker.java
@@ -11,8 +11,10 @@ package com.gemstone.gemfire.management.internal.web.shell;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 
 import com.gemstone.gemfire.internal.lang.Filter;
 import com.gemstone.gemfire.internal.lang.Initable;
@@ -22,6 +24,7 @@ import com.gemstone.gemfire.internal.util.CollectionUtils;
 import com.gemstone.gemfire.management.internal.cli.CommandRequest;
 import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
 import com.gemstone.gemfire.management.internal.web.domain.Link;
 import com.gemstone.gemfire.management.internal.web.domain.LinkIndex;
 import com.gemstone.gemfire.management.internal.web.http.ClientHttpRequest;
@@ -65,6 +68,7 @@ public class RestHttpOperationInvoker extends AbstractHttpOperationInvoker imple
   // the LinkIndex containing Links to all GemFire REST API web service endpoints
   private final LinkIndex linkIndex;
 
+
   /**
    * Constructs an instance of the RestHttpOperationInvoker class initialized with the given link index containing links
    * referencing all REST API web service endpoints.  This constructor should only be used for testing purposes.
@@ -87,12 +91,12 @@ public class RestHttpOperationInvoker extends AbstractHttpOperationInvoker imple
    * 
    * @param linkIndex the LinkIndex containing Links to all REST API web service endpoints in GemFire' REST interface.
    * @param gfsh a reference to the instance of the GemFire shell using this OperationInvoker to process commands.
-   * @see #RestHttpOperationInvoker(com.gemstone.gemfire.management.internal.web.domain.LinkIndex, com.gemstone.gemfire.management.internal.cli.shell.Gfsh, String)
+   * @see #RestHttpOperationInvoker(com.gemstone.gemfire.management.internal.web.domain.LinkIndex, com.gemstone.gemfire.management.internal.cli.shell.Gfsh,  Map)
    * @see com.gemstone.gemfire.management.internal.cli.shell.Gfsh
    * @see com.gemstone.gemfire.management.internal.web.domain.LinkIndex
    */
-  public RestHttpOperationInvoker(final LinkIndex linkIndex, final Gfsh gfsh) {
-    this(linkIndex, gfsh, CliStrings.CONNECT__DEFAULT_BASE_URL);
+  public RestHttpOperationInvoker(final LinkIndex linkIndex, final Gfsh gfsh, Map<String,String> securityProperties) {
+    this(linkIndex, gfsh, CliStrings.CONNECT__DEFAULT_BASE_URL, securityProperties);
   }
 
   /**
@@ -108,11 +112,12 @@ public class RestHttpOperationInvoker extends AbstractHttpOperationInvoker imple
    * @see com.gemstone.gemfire.management.internal.web.domain.LinkIndex
    * @see com.gemstone.gemfire.management.internal.cli.shell.Gfsh
    */
-  public RestHttpOperationInvoker(final LinkIndex linkIndex, final Gfsh gfsh, final String baseUrl) {
-    super(gfsh, baseUrl);
+  public RestHttpOperationInvoker(final LinkIndex linkIndex, final Gfsh gfsh, final String baseUrl, Map<String,String> securityProperties) {
+    super(gfsh, baseUrl, securityProperties);
     assertNotNull(linkIndex, "The Link Index resolving commands to REST API web service endpoints cannot be null!");
     this.linkIndex = linkIndex;
-    this.httpOperationInvoker = new SimpleHttpOperationInvoker(gfsh, baseUrl);
+    this.httpOperationInvoker = new SimpleHttpOperationInvoker(gfsh, baseUrl, securityProperties);
+
   }
 
   /**
@@ -142,6 +147,14 @@ public class RestHttpOperationInvoker extends AbstractHttpOperationInvoker imple
             httpRequest.getHeaders().setAccept(getAcceptableMediaTypes());
             httpRequest.getHeaders().setContentLength(0l);
 
+            if(securityProperties != null){
+              Iterator<Entry<String, String>> it = securityProperties.entrySet().iterator();
+              while(it.hasNext()){
+                Entry<String,String> entry= it.next();
+                httpRequest.getHeaders().add(entry.getKey(), entry.getValue());
+              }
+            }
+
             ClientHttpResponse httpResponse = httpRequest.execute();
 
             if (HttpStatus.NOT_FOUND.equals(httpResponse.getStatusCode())) {
@@ -229,6 +242,7 @@ public class RestHttpOperationInvoker extends AbstractHttpOperationInvoker imple
       }
     }
 
+    
     if (command.getFileData() != null) {
       request.addParameterValues(RESOURCES_REQUEST_PARAMETER, (Object[]) ConvertUtils.convert(command.getFileData()));
     }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/SimpleHttpOperationInvoker.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/SimpleHttpOperationInvoker.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/SimpleHttpOperationInvoker.java
index a122339..3f5f18b 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/SimpleHttpOperationInvoker.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/web/shell/SimpleHttpOperationInvoker.java
@@ -9,6 +9,7 @@
 package com.gemstone.gemfire.management.internal.web.shell;
 
 import java.net.URI;
+import java.util.Map;
 
 import com.gemstone.gemfire.management.internal.cli.CommandRequest;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
@@ -54,11 +55,11 @@ public class SimpleHttpOperationInvoker extends AbstractHttpOperationInvoker {
    * using HTTP processing.
    * 
    * @param gfsh a reference to the instance of the GemFire shell using this OperationInvoker to process commands.
-   * @see #SimpleHttpOperationInvoker(com.gemstone.gemfire.management.internal.cli.shell.Gfsh, String)
+   * @see #SimpleHttpOperationInvoker(com.gemstone.gemfire.management.internal.cli.shell.Gfsh, String, Map)
    * @see com.gemstone.gemfire.management.internal.cli.shell.Gfsh
    */
-  public SimpleHttpOperationInvoker(final Gfsh gfsh) {
-    this(gfsh, REST_API_URL);
+  public SimpleHttpOperationInvoker(final Gfsh gfsh, Map<String,String> securityProperties) {
+    this(gfsh, REST_API_URL, securityProperties);
   }
 
   /**
@@ -71,8 +72,8 @@ public class SimpleHttpOperationInvoker extends AbstractHttpOperationInvoker {
    * @param baseUrl the base URL to the GemFire Manager's HTTP service.
    * @see com.gemstone.gemfire.management.internal.cli.shell.Gfsh
    */
-  public SimpleHttpOperationInvoker(final Gfsh gfsh, final String baseUrl) {
-    super(gfsh, baseUrl);
+  public SimpleHttpOperationInvoker(final Gfsh gfsh, final String baseUrl, Map<String,String> securityProperties) {
+    super(gfsh, baseUrl, securityProperties);
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/security/GeodeTokenService.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/security/GeodeTokenService.java b/gemfire-core/src/main/java/com/gemstone/gemfire/security/GeodeTokenService.java
new file mode 100644
index 0000000..2eb2d9a
--- /dev/null
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/security/GeodeTokenService.java
@@ -0,0 +1,101 @@
+/**
+ * 
+ */
+package com.gemstone.gemfire.security;
+
+import java.security.Principal;
+import java.util.Random;
+
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.CacheFactory;
+import com.gemstone.gemfire.cache.ExpirationAction;
+import com.gemstone.gemfire.cache.ExpirationAttributes;
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.RegionFactory;
+import com.gemstone.gemfire.cache.RegionShortcut;
+
+/**
+ * This implementation provides a simple token service, generating and managing
+ * string tokens based on <code>java.util.Random</code>. The generated tokens
+ * are stored in a Geode <code>Region</code>. Older or idle tokens are expired
+ * periodically.
+ * <p>
+ * A new token is issued with each invocation of
+ * {@link GeodeTokenService#validateToken(String, Principal)}.
+ */
+public class GeodeTokenService implements TokenService {
+
+  private Region<String, Principal> tokenStore;
+
+  private Random tokenGenerator = null;
+
+  private int seedBase;
+  
+  private long firstToken;
+
+  public GeodeTokenService() {
+    // Create a region with expiration attributes.
+    Cache cache = CacheFactory.getAnyInstance();
+    RegionFactory<String, Principal> rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
+
+    // Remove a token after 30 minutes.
+    rf.setEntryTimeToLive(new ExpirationAttributes(30*60, ExpirationAction.DESTROY));
+    // Remove idle tokens after 5 minutes.
+    rf.setEntryIdleTimeout(new ExpirationAttributes(5*60, ExpirationAction.DESTROY));
+    
+    this.tokenStore = rf.create("geode_token_store");
+
+    this.seedBase = cache.getDistributedSystem().getDistributedMember().hashCode();
+    initializeTokenGenerator();
+  }
+
+  private void initializeTokenGenerator() {
+    this.tokenGenerator = new Random(this.seedBase + System.currentTimeMillis());
+    this.firstToken = this.tokenGenerator.nextLong();
+  }
+
+  public static GeodeTokenService create() {
+    return new GeodeTokenService();
+  }
+
+  @Override
+  public String generateToken(Principal principal) {
+    String token = generateTokenString(principal);
+    this.tokenStore.put(token, principal);
+    return token;
+  }
+
+  @Override
+  public String validateToken(String token, Principal principal)
+      throws AuthenticationRequiredException, AuthenticationFailedException {
+    Principal savedPrincipal = this.tokenStore.get(token);
+
+    if (savedPrincipal != null && savedPrincipal.equals(principal)) {
+      // I know this guy. Refresh the token for this client.
+      this.tokenStore.remove(token);
+      token = generateTokenString(savedPrincipal);
+      this.tokenStore.put(token, savedPrincipal);
+      return token;
+    }
+
+    this.tokenStore.remove(token);
+    String msg = "Authentication failed.";
+
+    throw savedPrincipal == null ? new AuthenticationRequiredException(msg)
+        : new AuthenticationFailedException(msg);
+  }
+
+  private synchronized String generateTokenString(Principal principal) {
+    long token = this.tokenGenerator.nextLong();
+    if (token == this.firstToken) {
+      // We have run out of tokens. Re-initialise the token generator.
+      initializeTokenGenerator();
+      // Invalidate all the existing tokens and force authenticated REST clients
+      // to re-authenticate themselves.
+      this.tokenStore.clear();
+      token = this.tokenGenerator.nextLong();
+    }
+    return String.valueOf(token);
+  }
+
+}



[5/6] incubator-geode git commit: GEODE-77 : Integrated Security Code Merge Review board url : https://reviews.apache.org/r/37209/

Posted by tu...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DiskStoreCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DiskStoreCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DiskStoreCommands.java
index 4614ce7..cbb53ed 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DiskStoreCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DiskStoreCommands.java
@@ -86,6 +86,9 @@ import com.gemstone.gemfire.management.internal.cli.util.MemberNotFoundException
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
 import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
 import com.gemstone.gemfire.management.internal.messages.CompactRequest;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * The DiskStoreCommands class encapsulates all GemFire Disk Store commands in Gfsh.
@@ -114,6 +117,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
   
   @CliCommand(value=CliStrings.BACKUP_DISK_STORE, help=CliStrings.BACKUP_DISK_STORE__HELP)
   @CliMetaData(relatedTopic={ CliStrings.TOPIC_GEMFIRE_DISKSTORE })
+  @ResourceOperation(resource = Resource.DISKSTORE, operation= ResourceConstants.BACKUP_DISKSTORE)
   public Result backupDiskStore(
   
   @CliOption(key=CliStrings.BACKUP_DISK_STORE__DISKDIRS,
@@ -208,6 +212,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.LIST_DISK_STORE, help = CliStrings.LIST_DISK_STORE__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_DISKSTORE })
+  @ResourceOperation(resource = Resource.DISKSTORE, operation= ResourceConstants.LIST_DS)
   public Result listDiskStore() {
     try {
       Set<DistributedMember> dataMembers = getNormalMembers(getCache());
@@ -276,6 +281,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
 
   @CliCommand(value=CliStrings.CREATE_DISK_STORE, help=CliStrings.CREATE_DISK_STORE__HELP)
   @CliMetaData(shellOnly=false, relatedTopic={CliStrings.TOPIC_GEMFIRE_DISKSTORE}, writesToSharedConfiguration=true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.CREATE_DISKSTORE)
   public Result createDiskStore(@CliOption(key=CliStrings.CREATE_DISK_STORE__NAME, 
                                            mandatory=true,
                                            optionContext = ConverterHint.DISKSTORE_ALL, 
@@ -416,6 +422,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
     
   @CliCommand(value=CliStrings.COMPACT_DISK_STORE, help=CliStrings.COMPACT_DISK_STORE__HELP)
   @CliMetaData(shellOnly=false, relatedTopic={CliStrings.TOPIC_GEMFIRE_DISKSTORE})
+  @ResourceOperation(resource = Resource.DISKSTORE, operation= ResourceConstants.COMPACT_DISKSTORE)
   public Result compactDiskStore(@CliOption(key=CliStrings.COMPACT_DISK_STORE__NAME, 
                                             mandatory=true,
                                             optionContext = ConverterHint.DISKSTORE_ALL, 
@@ -545,6 +552,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
 
   @CliCommand(value=CliStrings.COMPACT_OFFLINE_DISK_STORE, help=CliStrings.COMPACT_OFFLINE_DISK_STORE__HELP)
   @CliMetaData(shellOnly=true, relatedTopic={CliStrings.TOPIC_GEMFIRE_DISKSTORE})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result compactOfflineDiskStore(
                  @CliOption(key=CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME, 
                             mandatory=true,
@@ -688,6 +696,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
   
   @CliCommand(value=CliStrings.UPGRADE_OFFLINE_DISK_STORE, help=CliStrings.UPGRADE_OFFLINE_DISK_STORE__HELP)
   @CliMetaData(shellOnly=true, relatedTopic={CliStrings.TOPIC_GEMFIRE_DISKSTORE})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result upgradeOfflineDiskStore(
       @CliOption(key=CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME, 
       mandatory=true,
@@ -857,6 +866,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.DESCRIBE_DISK_STORE, help = CliStrings.DESCRIBE_DISK_STORE__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_DISKSTORE })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result describeDiskStore(@CliOption(key = CliStrings.DESCRIBE_DISK_STORE__MEMBER, mandatory = true, optionContext = ConverterHint.MEMBERIDNAME, help = CliStrings.DESCRIBE_DISK_STORE__MEMBER__HELP)
                                   final String memberName,
                                   @CliOption(key = CliStrings.DESCRIBE_DISK_STORE__NAME, mandatory = true, optionContext = ConverterHint.DISKSTORE_ALL, help = CliStrings.DESCRIBE_DISK_STORE__NAME__HELP)
@@ -983,6 +993,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.REVOKE_MISSING_DISK_STORE, help = CliStrings.REVOKE_MISSING_DISK_STORE__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_GEMFIRE_DISKSTORE })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.REVOKE_MISSING_DISKSTORE)
   public Result revokeMissingDiskStore(
       @CliOption(key = CliStrings.REVOKE_MISSING_DISK_STORE__ID, mandatory = true, help = CliStrings.REVOKE_MISSING_DISK_STORE__ID__HELP)
       String id) {
@@ -1009,6 +1020,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.SHOW_MISSING_DISK_STORE, help = CliStrings.SHOW_MISSING_DISK_STORE__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_GEMFIRE_DISKSTORE })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result showMissingDiskStore() {
 
     try {
@@ -1047,6 +1059,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
   
   @CliCommand(value=CliStrings.DESCRIBE_OFFLINE_DISK_STORE, help=CliStrings.DESCRIBE_OFFLINE_DISK_STORE__HELP)
   @CliMetaData(shellOnly=true, relatedTopic={CliStrings.TOPIC_GEMFIRE_DISKSTORE})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result describeOfflineDiskStore(
       @CliOption (key=CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME, 
           mandatory=true,
@@ -1095,6 +1108,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
   
   @CliCommand(value=CliStrings.EXPORT_OFFLINE_DISK_STORE, help=CliStrings.EXPORT_OFFLINE_DISK_STORE__HELP)
   @CliMetaData(shellOnly=true, relatedTopic={CliStrings.TOPIC_GEMFIRE_DISKSTORE})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result exportOfflineDiskStore(
       @CliOption (key=CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKSTORENAME, 
           mandatory=true,
@@ -1143,6 +1157,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
 
   @CliCommand(value=CliStrings.VALIDATE_DISK_STORE, help=CliStrings.VALIDATE_DISK_STORE__HELP)
   @CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_DISKSTORE}) //offline command
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result validateDiskStore(
       @CliOption(key=CliStrings.VALIDATE_DISK_STORE__NAME, mandatory=true,
                   help=CliStrings.VALIDATE_DISK_STORE__NAME__HELP)
@@ -1206,7 +1221,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
   
   @CliCommand(value=CliStrings.ALTER_DISK_STORE, help=CliStrings.ALTER_DISK_STORE__HELP)
   @CliMetaData(shellOnly=true, relatedTopic={CliStrings.TOPIC_GEMFIRE_DISKSTORE})
-  
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result alterOfflineDiskStore(
       @CliOption  (key=CliStrings.ALTER_DISK_STORE__DISKSTORENAME, 
       mandatory=true,
@@ -1338,6 +1353,7 @@ public class DiskStoreCommands extends AbstractCommandsSupport {
 
   @CliCommand(value=CliStrings.DESTROY_DISK_STORE, help=CliStrings.DESTROY_DISK_STORE__HELP)
   @CliMetaData(shellOnly=false, relatedTopic={CliStrings.TOPIC_GEMFIRE_DISKSTORE}, writesToSharedConfiguration=true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.DESTROY_DISKSTORE)
   public Result destroyDiskStore(
       @CliOption  (key=CliStrings.DESTROY_DISK_STORE__NAME, 
           mandatory=true,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DurableClientCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DurableClientCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DurableClientCommands.java
index 01910d6..3cc0947 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DurableClientCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DurableClientCommands.java
@@ -48,6 +48,9 @@ import com.gemstone.gemfire.management.internal.cli.result.InfoResultData;
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.ResultData;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * The DurableClientCommands class encapsulates all GemFire shell (Gfsh) commands related to 
@@ -66,6 +69,7 @@ public class DurableClientCommands extends AbstractCommandsSupport {
 
 	@CliCommand(value = CliStrings.LIST_DURABLE_CQS, help = CliStrings.LIST_DURABLE_CQS__HELP)
 	@CliMetaData(shellOnly = false)
+	@ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
 	public Result listDurableClientCqs(
 	@CliOption (key = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID,
 	mandatory=true,
@@ -142,6 +146,7 @@ public class DurableClientCommands extends AbstractCommandsSupport {
 
 	@CliCommand(value = CliStrings.COUNT_DURABLE_CQ_EVENTS, help = CliStrings.COUNT_DURABLE_CQ_EVENTS__HELP)
 	@CliMetaData(shellOnly = false)
+	@ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
 	public Result countDurableCqEvents(
 	@CliOption (key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID,
 	mandatory=true,
@@ -193,6 +198,7 @@ public class DurableClientCommands extends AbstractCommandsSupport {
 
 	@CliCommand(value = CliStrings.CLOSE_DURABLE_CLIENTS, help = CliStrings.CLOSE_DURABLE_CLIENTS__HELP)
 	@CliMetaData(shellOnly = false)
+	@ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.CLOSE_DURABLE_CLIENT)
 	public Result closeDurableClient(
 	@CliOption (key = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID,
 				mandatory=true,
@@ -231,6 +237,7 @@ public class DurableClientCommands extends AbstractCommandsSupport {
 	
 	@CliCommand(value = CliStrings.CLOSE_DURABLE_CQS, help = CliStrings.CLOSE_DURABLE_CQS__HELP)
 	@CliMetaData(shellOnly = false)
+	@ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.CLOSE_DURABLE_CQ)
 	public Result closeDurableCqs(
 	@CliOption (key = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID,
 	mandatory=true,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ExportImportSharedConfigurationCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ExportImportSharedConfigurationCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ExportImportSharedConfigurationCommands.java
index d4134ad..c9a553a 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ExportImportSharedConfigurationCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ExportImportSharedConfigurationCommands.java
@@ -34,6 +34,9 @@ import com.gemstone.gemfire.management.internal.cli.result.FileResult;
 import com.gemstone.gemfire.management.internal.cli.result.InfoResultData;
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
 import org.springframework.shell.core.annotation.CliCommand;
@@ -53,6 +56,7 @@ public class ExportImportSharedConfigurationCommands extends AbstractCommandsSup
 
   @CliCommand(value = { CliStrings.EXPORT_SHARED_CONFIG }, help = CliStrings.EXPORT_SHARED_CONFIG__HELP)
   @CliMetaData(interceptor = "com.gemstone.gemfire.management.internal.cli.commands.ExportImportSharedConfigurationCommands$ExportInterceptor",  readsSharedConfiguration=true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_CONFIG})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.EXPORT_CONFIG)
   public Result exportSharedConfig(
       @CliOption(key = { CliStrings.EXPORT_SHARED_CONFIG__FILE}, 
       mandatory = true,
@@ -103,6 +107,7 @@ public class ExportImportSharedConfigurationCommands extends AbstractCommandsSup
 
   @CliCommand(value = { CliStrings.IMPORT_SHARED_CONFIG }, help = CliStrings.IMPORT_SHARED_CONFIG__HELP)
   @CliMetaData(interceptor = "com.gemstone.gemfire.management.internal.cli.commands.ExportImportSharedConfigurationCommands$ImportInterceptor", writesToSharedConfiguration=true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_CONFIG})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.IMPORT_CONFIG)
   @SuppressWarnings("unchecked")
   public Result importSharedConfig(
       @CliOption(key = { CliStrings.IMPORT_SHARED_CONFIG__ZIP},

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/FunctionCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/FunctionCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/FunctionCommands.java
index 0d8c54a..105bd2d 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/FunctionCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/FunctionCommands.java
@@ -55,6 +55,9 @@ import com.gemstone.gemfire.management.internal.cli.result.ErrorResultData;
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * @author David Hoots
@@ -71,6 +74,7 @@ public class FunctionCommands implements CommandMarker {
   
   @CliCommand(value = CliStrings.EXECUTE_FUNCTION, help = CliStrings.EXECUTE_FUNCTION__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_GEMFIRE_FUNCTION })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.EXECUTE_FUNCTION)
   public Result executeFunction(
       //TODO: Add optioncontext for functionID
       @CliOption(key = CliStrings.EXECUTE_FUNCTION__ID, 
@@ -442,7 +446,8 @@ public class FunctionCommands implements CommandMarker {
   
   @CliCommand(value = CliStrings.DESTROY_FUNCTION, help = CliStrings.DESTROY_FUNCTION__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_GEMFIRE_FUNCTION } ,
-      interceptor = "com.gemstone.gemfire.management.internal.cli.commands.FunctionCommands$Interceptor")  
+      interceptor = "com.gemstone.gemfire.management.internal.cli.commands.FunctionCommands$Interceptor")
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.DESTROY_FUNCTION)
   //TODO: Add optioncontext for functionId
   public Result destroyFunction(
       @CliOption(key = CliStrings.DESTROY_FUNCTION__ID, 
@@ -566,6 +571,7 @@ public class FunctionCommands implements CommandMarker {
   
   @CliCommand(value = CliStrings.LIST_FUNCTION, help = CliStrings.LIST_FUNCTION__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_GEMFIRE_FUNCTION })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result listFunction(
       @CliOption(key = CliStrings.LIST_FUNCTION__MATCHES, 
                  help = CliStrings.LIST_FUNCTION__MATCHES__HELP)String matches,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/GfshHelpCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/GfshHelpCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/GfshHelpCommands.java
index d9d4bea..3a80dee 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/GfshHelpCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/GfshHelpCommands.java
@@ -27,6 +27,9 @@ import com.gemstone.gemfire.management.internal.cli.result.CompositeResultData;
 import com.gemstone.gemfire.management.internal.cli.result.CompositeResultData.SectionResultData;
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * 
@@ -43,6 +46,7 @@ public class GfshHelpCommands implements CommandMarker{
   
   @CliCommand(value = CliStrings.HELP, help = CliStrings.HELP__HELP)
   @CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_HELP})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result obtainHelp(
       @CliArgument(name = CliStrings.HELP__COMMAND, 
                  argumentContext = CliStrings.PARAM_CONTEXT_HELP, 
@@ -55,6 +59,7 @@ public class GfshHelpCommands implements CommandMarker{
   
   @CliCommand(value = CliStrings.HINT, help = CliStrings.HINT__HELP)
   @CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_HELP})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result hint(
       @CliArgument(name = CliStrings.HINT__TOPICNAME, 
                 argumentContext = ConverterHint.HINTTOPIC, 

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/HDFSStoreCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/HDFSStoreCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/HDFSStoreCommands.java
index 6e573f1..6bc5e5d 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/HDFSStoreCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/HDFSStoreCommands.java
@@ -42,6 +42,9 @@ import com.gemstone.gemfire.management.internal.cli.util.HDFSStoreNotFoundExcept
 import com.gemstone.gemfire.management.internal.cli.util.MemberNotFoundException;
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
 import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * The HdfsStoreCommands class encapsulates all GemFire Hdfs Store commands in Gfsh.
@@ -55,6 +58,7 @@ import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
 public class HDFSStoreCommands   extends AbstractCommandsSupport {  
   @CliCommand (value = CliStrings.CREATE_HDFS_STORE, help = CliStrings.CREATE_HDFS_STORE__HELP)
   @CliMetaData (relatedTopic = CliStrings.TOPIC_GEMFIRE_HDFSSTORE, writesToSharedConfiguration = true)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.CREATE_HDFS_STORE)
   public Result createHdfsStore(      
       @CliOption (key = CliStrings.CREATE_HDFS_STORE__NAME,                  
                   mandatory = true,
@@ -290,6 +294,7 @@ public class HDFSStoreCommands   extends AbstractCommandsSupport {
   
   @CliCommand(value = CliStrings.DESCRIBE_HDFS_STORE, help = CliStrings.DESCRIBE_HDFS_STORE__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_HDFSSTORE})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result describeHdfsStore(
       @CliOption(key = CliStrings.DESCRIBE_HDFS_STORE__MEMBER, 
                  mandatory = true, optionContext = ConverterHint.MEMBERIDNAME, 
@@ -380,6 +385,7 @@ public class HDFSStoreCommands   extends AbstractCommandsSupport {
   
   @CliCommand(value = CliStrings.LIST_HDFS_STORE, help = CliStrings.LIST_HDFS_STORE__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_HDFSSTORE })
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result listHdfsStore() {  
     try {
       Set<DistributedMember> dataMembers = getNormalMembers(getCache());
@@ -457,6 +463,7 @@ public class HDFSStoreCommands   extends AbstractCommandsSupport {
 
   @CliCommand(value=CliStrings.DESTROY_HDFS_STORE, help=CliStrings.DESTROY_HDFS_STORE__HELP)
   @CliMetaData(shellOnly=false, relatedTopic={CliStrings.TOPIC_GEMFIRE_HDFSSTORE}, writesToSharedConfiguration=true)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.DESTROY_HDFS_STORE)
   public Result destroyHdfstore(
       @CliOption  (key=CliStrings.DESTROY_HDFS_STORE__NAME, 
                    optionContext=ConverterHint.HDFSSTORE_ALL,
@@ -536,6 +543,7 @@ public class HDFSStoreCommands   extends AbstractCommandsSupport {
   }
   @CliCommand(value=CliStrings.ALTER_HDFS_STORE, help=CliStrings.ALTER_HDFS_STORE__HELP)
   @CliMetaData(shellOnly=false, relatedTopic={CliStrings.TOPIC_GEMFIRE_HDFSSTORE}, writesToSharedConfiguration=true)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.ALTER_HDFS_STORE)
   public Result alterHdfstore(
       @CliOption (key = CliStrings.ALTER_HDFS_STORE__NAME,                  
           mandatory = true,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/IndexCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/IndexCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/IndexCommands.java
index c978381..31a3eec 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/IndexCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/IndexCommands.java
@@ -53,6 +53,9 @@ import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
 import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * The IndexCommands class encapsulates all GemFire shell (Gfsh) commands related to indexes defined in GemFire.
@@ -79,6 +82,7 @@ public class IndexCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.LIST_INDEX, help = CliStrings.LIST_INDEX__HELP)
   @CliMetaData(shellOnly = false, relatedTopic={CliStrings.TOPIC_GEMFIRE_REGION, CliStrings.TOPIC_GEMFIRE_DATA})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result listIndex(@CliOption(key = CliStrings.LIST_INDEX__STATS,
                                      mandatory = false,
                                      specifiedDefaultValue = "true",
@@ -162,6 +166,7 @@ public class IndexCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.CREATE_INDEX, help = CliStrings.CREATE_INDEX__HELP)
   @CliMetaData(shellOnly = false, relatedTopic={CliStrings.TOPIC_GEMFIRE_REGION, CliStrings.TOPIC_GEMFIRE_DATA}, writesToSharedConfiguration=true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.CREATE_INDEX)
   //TODO : Add optionContext for indexName
   public Result createIndex(
       @CliOption (key = CliStrings.CREATE_INDEX__NAME,
@@ -311,6 +316,7 @@ public class IndexCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.DESTROY_INDEX, help = CliStrings.DESTROY_INDEX__HELP)
   @CliMetaData(shellOnly = false, relatedTopic={CliStrings.TOPIC_GEMFIRE_REGION, CliStrings.TOPIC_GEMFIRE_DATA}, writesToSharedConfiguration=true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.DESTROY_INDEX)
   //TODO : Add optioncontext for the index name. 
   public Result destroyIndex(
       @CliOption(
@@ -447,6 +453,7 @@ public class IndexCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.DEFINE_INDEX, help = CliStrings.DEFINE_INDEX__HELP)
   @CliMetaData(shellOnly = false, relatedTopic={CliStrings.TOPIC_GEMFIRE_REGION, CliStrings.TOPIC_GEMFIRE_DATA}, writesToSharedConfiguration=true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.CREATE_INDEX)
   //TODO : Add optionContext for indexName
   public Result defineIndex(
       @CliOption (key = CliStrings.DEFINE_INDEX_NAME,
@@ -515,6 +522,7 @@ public class IndexCommands extends AbstractCommandsSupport {
   
   @CliCommand(value = CliStrings.CREATE_DEFINED_INDEXES, help = CliStrings.CREATE_DEFINED__HELP)
   @CliMetaData(shellOnly = false, relatedTopic={CliStrings.TOPIC_GEMFIRE_REGION, CliStrings.TOPIC_GEMFIRE_DATA}, writesToSharedConfiguration=true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.CREATE_INDEX)
   //TODO : Add optionContext for indexName
   public Result createDefinedIndexes(
 
@@ -615,6 +623,7 @@ public class IndexCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.CLEAR_DEFINED_INDEXES, help = CliStrings.CLEAR_DEFINED__HELP)
   @CliMetaData(shellOnly = false, relatedTopic={CliStrings.TOPIC_GEMFIRE_REGION, CliStrings.TOPIC_GEMFIRE_DATA}, writesToSharedConfiguration=true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.CREATE_INDEX)
   //TODO : Add optionContext for indexName
   public Result clearDefinedIndexes() {
     indexDefinitions.clear();

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/LauncherLifecycleCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/LauncherLifecycleCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/LauncherLifecycleCommands.java
index 302d7bb..591ac84 100755
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/LauncherLifecycleCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/LauncherLifecycleCommands.java
@@ -104,6 +104,11 @@ import com.gemstone.gemfire.management.internal.cli.util.VisualVmNotFoundExcepti
 import com.gemstone.gemfire.management.internal.configuration.domain.SharedConfigurationStatus;
 import com.gemstone.gemfire.management.internal.configuration.messages.SharedConfigurationStatusRequest;
 import com.gemstone.gemfire.management.internal.configuration.messages.SharedConfigurationStatusResponse;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
+import com.gemstone.gemfire.security.GemFireSecurityException;
+//import com.gemstone.org.jgroups.stack.tcpserver.TcpClient;
 import com.sun.tools.attach.VirtualMachine;
 import com.sun.tools.attach.VirtualMachineDescriptor;
 
@@ -194,6 +199,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.START_LOCATOR, help = CliStrings.START_LOCATOR__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEMFIRE_LOCATOR, CliStrings.TOPIC_GEMFIRE_LIFECYCLE })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result startLocator(@CliOption(key = CliStrings.START_LOCATOR__MEMBER_NAME,
                                         mandatory = true,
                                         unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
@@ -599,7 +605,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
         }
 
         getGfsh().setOperationInvoker(new JmxOperationInvoker(memberEndpoint.getHost(), memberEndpoint.getPort(),
-          null, null, configurationProperties));
+          null, null, configurationProperties, null));
 
         String shellAndLogMessage = CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, memberEndpoint.toString(false));
 
@@ -774,6 +780,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.STATUS_LOCATOR, help = CliStrings.STATUS_LOCATOR__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEMFIRE_LOCATOR, CliStrings.TOPIC_GEMFIRE_LIFECYCLE })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result statusLocator(@CliOption(key = CliStrings.STATUS_LOCATOR__MEMBER,
                                          optionContext = ConverterHint.LOCATOR_MEMBER_IDNAME,
                                          unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
@@ -850,6 +857,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value=CliStrings.STOP_LOCATOR, help=CliStrings.STOP_LOCATOR__HELP)
   @CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_LOCATOR, CliStrings.TOPIC_GEMFIRE_LIFECYCLE})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result stopLocator(@CliOption(key = CliStrings.STOP_LOCATOR__MEMBER,
                                        optionContext = ConverterHint.LOCATOR_MEMBER_IDNAME,
                                        unspecifiedDefaultValue=CliMetaData.ANNOTATION_NULL_VALUE,
@@ -1365,6 +1373,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.START_SERVER, help = CliStrings.START_SERVER__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEMFIRE_SERVER, CliStrings.TOPIC_GEMFIRE_LIFECYCLE })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result startServer(@CliOption(key = CliStrings.START_SERVER__ASSIGN_BUCKETS,
                                       unspecifiedDefaultValue = "false",
                                       specifiedDefaultValue = "true",
@@ -1931,6 +1940,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.STATUS_SERVER, help = CliStrings.STATUS_SERVER__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEMFIRE_SERVER, CliStrings.TOPIC_GEMFIRE_LIFECYCLE })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result statusServer(@CliOption(key = CliStrings.STATUS_SERVER__MEMBER,
                                         optionContext = ConverterHint.MEMBERIDNAME,
                                         unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
@@ -2001,6 +2011,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.STOP_SERVER, help = CliStrings.STOP_SERVER__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEMFIRE_SERVER, CliStrings.TOPIC_GEMFIRE_LIFECYCLE })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result stopServer(@CliOption(key = CliStrings.STOP_SERVER__MEMBER,
                                       optionContext = ConverterHint.MEMBERIDNAME,
                                       unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
@@ -2097,6 +2108,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   //@CliCommand(value=CliStrings.START_MANAGER, help=CliStrings.START_MANAGER__HELP)
   //@CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_MANAGER, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_LIFECYCLE})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result startManager(@CliOption(key=CliStrings.START_MANAGER__MEMBERNAME,
                               unspecifiedDefaultValue=CliMetaData.ANNOTATION_NULL_VALUE,
                               help=CliStrings.START_MANAGER__MEMBERNAME__HELP)
@@ -2139,6 +2151,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.START_JCONSOLE, help = CliStrings.START_JCONSOLE__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEMFIRE_MANAGER, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_M_AND_M })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result startJConsole(@CliOption(key = CliStrings.START_JCONSOLE__INTERVAL,
                                          unspecifiedDefaultValue = "4",
                                          help = CliStrings.START_JCONSOLE__INTERVAL__HELP)
@@ -2332,6 +2345,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.START_JVISUALVM, help = CliStrings.START_JVISUALVM__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEMFIRE_MANAGER, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_M_AND_M })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result startJVisualVM(@CliOption(key = CliStrings.START_JCONSOLE__J,
                                           optionContext = ConverterHint.STRING_LIST,
                                           unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
@@ -2421,6 +2435,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = CliStrings.START_PULSE, help = CliStrings.START_PULSE__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEMFIRE_MANAGER, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_M_AND_M })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   // TODO change url parameter type to URL when I figure out the Converter logic in Gfsh
   public Result startPulse(@CliOption(key = CliStrings.START_PULSE__URL,
                                       unspecifiedDefaultValue = "http://localhost:7070/pulse",
@@ -2512,6 +2527,7 @@ public class LauncherLifecycleCommands extends AbstractCommandsSupport {
 
   @CliCommand(value=CliStrings.START_VSD, help=CliStrings.START_VSD__HELP)
   @CliMetaData(shellOnly=true, relatedTopic = { CliStrings.TOPIC_GEMFIRE_M_AND_M, CliStrings.TOPIC_GEMFIRE_STATISTICS })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result startVsd(@CliOption(key=CliStrings.START_VSD__FILE, help=CliStrings.START_VSD__FILE__HELP)
                          final String[] statisticsArchiveFilePathnames)
   {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MemberCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MemberCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MemberCommands.java
index 797f654..1d1f628 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MemberCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MemberCommands.java
@@ -39,6 +39,9 @@ import com.gemstone.gemfire.management.internal.cli.result.CompositeResultData.S
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /***
  *
@@ -54,6 +57,7 @@ public class MemberCommands implements CommandMarker {
 
   @CliCommand(value = { CliStrings.LIST_MEMBER }, help = CliStrings.LIST_MEMBER__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = CliStrings.TOPIC_GEMFIRE_SERVER)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result listMember(
 		  @CliOption(key = { CliStrings.LIST_MEMBER__GROUP },
 		             unspecifiedDefaultValue = "",
@@ -98,6 +102,7 @@ public class MemberCommands implements CommandMarker {
 
   @CliCommand(value = { CliStrings.DESCRIBE_MEMBER }, help = CliStrings.DESCRIBE_MEMBER__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = CliStrings.TOPIC_GEMFIRE_SERVER)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result describeMember(
   	@CliOption(key = CliStrings.DESCRIBE_MEMBER__IDENTIFIER,
   	             optionContext = ConverterHint.ALL_MEMBER_IDNAME,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MiscellaneousCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MiscellaneousCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MiscellaneousCommands.java
index da8f11d..25cf44f 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MiscellaneousCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/MiscellaneousCommands.java
@@ -181,7 +181,7 @@ public class MiscellaneousCommands implements CommandMarker {
   @CliCommand(value = CliStrings.SHUTDOWN, help = CliStrings.SHUTDOWN__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_GEMFIRE_LIFECYCLE },
       interceptor = "com.gemstone.gemfire.management.internal.cli.commands.MiscellaneousCommands$Interceptor")
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.SHUTDOWN_DS)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.SHUTDOWN)
   public Result shutdown(
       @CliOption(key = CliStrings.SHUTDOWN__TIMEOUT, unspecifiedDefaultValue = DEFAULT_TIME_OUT,
           help = CliStrings.SHUTDOWN__TIMEOUT__HELP) int userSpecifiedTimeout,
@@ -322,6 +322,7 @@ public class MiscellaneousCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.GC, help = CliStrings.GC__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.GC)
   public Result gc(
       @CliOption(key = CliStrings.GC__GROUP, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.GC__GROUP__HELP)
       String[] groups,
@@ -406,6 +407,7 @@ public class MiscellaneousCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.NETSTAT, help = CliStrings.NETSTAT__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.NETSTAT)
   //TODO : Verify the auto-completion for multiple values.
   public Result netstat(
       @CliOption(key = CliStrings.NETSTAT__MEMBER,
@@ -559,6 +561,7 @@ public class MiscellaneousCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.SHOW_DEADLOCK, help = CliStrings.SHOW_DEADLOCK__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.SHOW_DEADLOCKS)
   public Result showDeadlock(
       @CliOption(key = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE,
       help = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE__HELP,
@@ -597,6 +600,7 @@ public class MiscellaneousCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.SHOW_LOG, help = CliStrings.SHOW_LOG_HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.SHOW_LOG)
   public Result showLog(
       @CliOption(key = CliStrings.SHOW_LOG_MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.SHOW_LOG_MEMBER_HELP, mandatory = true) String memberNameOrId,
       @CliOption(key = CliStrings.SHOW_LOG_LINE_NUM, unspecifiedDefaultValue = "0", help = CliStrings.SHOW_LOG_LINE_NUM_HELP, mandatory = false) int numberOfLines) {
@@ -744,6 +748,7 @@ public class MiscellaneousCommands implements CommandMarker {
   }
   @CliCommand(value = CliStrings.EXPORT_LOGS, help = CliStrings.EXPORT_LOGS__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_SERVER, CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.EXPORT_LOGS)
   public Result exportLogs(
       @CliOption(key = CliStrings.EXPORT_LOGS__DIR,
           help = CliStrings.EXPORT_LOGS__DIR__HELP, mandatory=true) String dirName,
@@ -965,6 +970,7 @@ public class MiscellaneousCommands implements CommandMarker {
    */
   @CliCommand(value = CliStrings.EXPORT_STACKTRACE, help = CliStrings.EXPORT_STACKTRACE__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.EXPORT_STACKTRACE)
   public Result exportStackTrace(
       @CliOption(key = CliStrings.EXPORT_STACKTRACE__MEMBER,
       optionContext = ConverterHint.ALL_MEMBER_IDNAME,
@@ -1065,6 +1071,7 @@ public class MiscellaneousCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.SHOW_METRICS, help = CliStrings.SHOW_METRICS__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_STATISTICS })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.SHOW_METRICS)
   public Result showMetrics(
       @CliOption(key = { CliStrings.SHOW_METRICS__MEMBER }, optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.SHOW_METRICS__MEMBER__HELP) String memberNameOrId,
       @CliOption(key = { CliStrings.SHOW_METRICS__REGION }, optionContext = ConverterHint.REGIONPATH, help = CliStrings.SHOW_METRICS__REGION__HELP) String regionName,
@@ -1968,7 +1975,7 @@ public class MiscellaneousCommands implements CommandMarker {
   
   @CliCommand(value = CliStrings.CHANGE_LOGLEVEL, help = CliStrings.CHANGE_LOGLEVEL__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_CHANGELOGLEVEL })
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.CHANGE_ALERT_LEVEL_DS)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.CHANGE_ALERT_LEVEL)
   public Result changeLogLevel(
       @CliOption(key = CliStrings.CHANGE_LOGLEVEL__MEMBER, unspecifiedDefaultValue = "", help = CliStrings.CHANGE_LOGLEVEL__MEMBER__HELP) String[] memberIds, 
       @CliOption(key = CliStrings.CHANGE_LOGLEVEL__GROUPS, unspecifiedDefaultValue = "", help = CliStrings.CHANGE_LOGLEVEL__GROUPS__HELP) String[] grps,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/PDXCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/PDXCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/PDXCommands.java
index d236d81..90a0a93 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/PDXCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/PDXCommands.java
@@ -25,6 +25,9 @@ import com.gemstone.gemfire.management.internal.cli.result.InfoResultData;
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
 import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 import com.gemstone.gemfire.pdx.ReflectionBasedAutoSerializer;
 import com.gemstone.gemfire.pdx.internal.EnumInfo;
 import com.gemstone.gemfire.pdx.internal.PdxType;
@@ -34,6 +37,7 @@ public class PDXCommands extends AbstractCommandsSupport{
 
   @CliCommand (value = CliStrings.CONFIGURE_PDX, help = CliStrings.CONFIGURE_PDX__HELP)
   @CliMetaData (relatedTopic = CliStrings.TOPIC_GEMFIRE_REGION, writesToSharedConfiguration = true)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.CONFIGURE_PDX)
   public Result configurePDX( 
       @CliOption (key = CliStrings.CONFIGURE_PDX__READ__SERIALIZED,
       unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
@@ -155,6 +159,7 @@ public class PDXCommands extends AbstractCommandsSupport{
 
   @CliCommand (value = CliStrings.PDX_RENAME, help = CliStrings.PDX_RENAME__HELP)
   @CliMetaData(shellOnly=true, relatedTopic={CliStrings.TOPIC_GEMFIRE_DISKSTORE})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.RENAME_PDX)
   public Result pdxRename( 
       @CliOption (key = CliStrings.PDX_RENAME_OLD,
       mandatory=true,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/QueueCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/QueueCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/QueueCommands.java
index b59f38a..50e1d53 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/QueueCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/QueueCommands.java
@@ -37,6 +37,9 @@ import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
 import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * The QueueCommands class encapsulates all GemFire Queue commands in Gfsh.
@@ -52,6 +55,7 @@ public class QueueCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.CREATE_ASYNC_EVENT_QUEUE, help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__HELP)
   @CliMetaData(writesToSharedConfiguration = true)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.CREATE_AEQ)
   public Result createAsyncEventQueue(
       @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, 
                  mandatory = true,
@@ -191,6 +195,7 @@ public class QueueCommands implements CommandMarker {
   }
 
   @CliCommand(value = CliStrings.LIST_ASYNC_EVENT_QUEUES, help = CliStrings.LIST_ASYNC_EVENT_QUEUES__HELP)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result listAsyncEventQueues() {
     try {
       TabularResultData tabularData = ResultBuilder.createTabularResultData();

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/RegionCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/RegionCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/RegionCommands.java
index 80ba89e..6b70616 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/RegionCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/RegionCommands.java
@@ -46,6 +46,9 @@ import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
 import com.gemstone.gemfire.management.internal.cli.util.RegionAttributesNames;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /***
  * Class containing implementation of commands based on region:
@@ -67,6 +70,7 @@ public class RegionCommands implements CommandMarker {
 
   @CliCommand(value = { CliStrings.LIST_REGION }, help = CliStrings.LIST_REGION__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = CliStrings.TOPIC_GEMFIRE_REGION)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result listRegion(
       @CliOption(key = { CliStrings.LIST_REGION__GROUP },
       optionContext = ConverterHint.MEMBERGROUP,
@@ -146,6 +150,7 @@ public class RegionCommands implements CommandMarker {
 
   @CliCommand(value = { CliStrings.DESCRIBE_REGION }, help = CliStrings.DESCRIBE_REGION__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEMFIRE_REGION, CliStrings.TOPIC_GEMFIRE_CONFIG } )
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result describeRegion(
       @CliOption(key = CliStrings.DESCRIBE_REGION__NAME,
       optionContext = ConverterHint.REGIONPATH,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommands.java
index 4bdab90..d173c97 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommands.java
@@ -22,6 +22,7 @@ import java.net.MalformedURLException;
 import java.net.URL;
 import java.security.KeyStore;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
@@ -74,6 +75,9 @@ import com.gemstone.gemfire.management.internal.cli.shell.OperationInvoker;
 import com.gemstone.gemfire.management.internal.cli.shell.jline.GfshHistory;
 import com.gemstone.gemfire.management.internal.cli.util.CauseFinder;
 import com.gemstone.gemfire.management.internal.cli.util.ConnectionEndpoint;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 import com.gemstone.gemfire.management.internal.web.domain.LinkIndex;
 import com.gemstone.gemfire.management.internal.web.http.support.SimpleHttpRequester;
 import com.gemstone.gemfire.management.internal.web.shell.HttpOperationInvoker;
@@ -92,6 +96,7 @@ public class ShellCommands implements CommandMarker {
 
   @CliCommand(value = { CliStrings.EXIT, "quit" }, help = CliStrings.EXIT__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public ExitShellRequest exit() throws IOException {
     Gfsh gfshInstance = getGfsh();
 
@@ -115,6 +120,7 @@ public class ShellCommands implements CommandMarker {
 
   @CliCommand(value = { CliStrings.CONNECT }, help = CliStrings.CONNECT__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_MANAGER})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result connect(
     @CliOption(key = { CliStrings.CONNECT__LOCATOR },
                unspecifiedDefaultValue = ConnectionEndpointConverter.DEFAULT_LOCATOR_ENDPOINTS,
@@ -187,7 +193,17 @@ public class ShellCommands implements CommandMarker {
           ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage()));
       }
     } else if (useHttp) {      
+      Gfsh gemfireShell = getGfsh();
       try{
+    	  
+        if (userName != null && userName.length() > 0) {
+          if (passwordToUse == null || passwordToUse.length() == 0) {
+            passwordToUse = gemfireShell.readWithMask("http password: ", '*');
+          }
+          if (passwordToUse == null || passwordToUse.length() == 0) {
+            throw new IllegalArgumentException(CliStrings.CONNECT__MSG__JMX_PASSWORD_MUST_BE_SPECIFIED);
+          }
+        }
         
         final Map<String, String> sslConfigProps = this.readSSLConfiguration(useSsl, keystoreToUse,keystorePasswordToUse, 
             truststoreToUse, truststorePasswordToUse, sslCiphersToUse, sslProtocolsToUse, gfSecurityPropertiesPath);
@@ -199,15 +215,23 @@ public class ShellCommands implements CommandMarker {
           }
         }
         
+        Map<String,String> securityProperties = new HashMap<String, String>();
+        
+        Iterator<String> it = sslConfigProps.keySet().iterator();
+        while(it.hasNext()){
+          String secKey = it.next();
+          securityProperties.put(secKey, sslConfigProps.get(secKey));
+        }
+        
         LogWrapper.getInstance().warning(String.format("Sending HTTP request for Link Index at (%1$s)...", url.concat("/index")));
 
-        LinkIndex linkIndex = new SimpleHttpRequester(CONNECT_LOCATOR_TIMEOUT_MS).get(url.concat("/index"), LinkIndex.class);
+        LinkIndex linkIndex = new SimpleHttpRequester(gemfireShell, CONNECT_LOCATOR_TIMEOUT_MS, securityProperties).exchange(url.concat("/index"), LinkIndex.class);
 
         LogWrapper.getInstance().warning(String.format("Received Link Index (%1$s)", linkIndex.toString()));
 
-        Gfsh gemfireShell = getGfsh();
+        
 
-        HttpOperationInvoker operationInvoker = new RestHttpOperationInvoker(linkIndex, gemfireShell, url);
+        HttpOperationInvoker operationInvoker = new RestHttpOperationInvoker(linkIndex, gemfireShell, url, securityProperties);
 
         Initializer.init(operationInvoker);
         gemfireShell.setOperationInvoker(operationInvoker);
@@ -220,11 +244,11 @@ public class ShellCommands implements CommandMarker {
       } catch (IOException ioe) {
         String errorMessage = ioe.getMessage();
         result = ResultBuilder.createConnectionErrorResult(errorMessage);
-        ioe.printStackTrace();
+        if (gemfireShell.getDebug()) {ioe.printStackTrace();}
       } catch (Exception e) {
         String errorMessage = e.getMessage();
         result = ResultBuilder.createConnectionErrorResult(errorMessage);
-        e.printStackTrace();
+        if (gemfireShell.getDebug()) {e.printStackTrace();}
       }
     } else {
 
@@ -289,7 +313,7 @@ public class ShellCommands implements CommandMarker {
           gfshInstance.logToFile("Connecting to manager via SSL.", null);
         }
 
-        JmxOperationInvoker operationInvoker = new JmxOperationInvoker(memberRmiHostPort.getHost(), memberRmiHostPort.getPort(), userName, passwordToUse, sslConfigProps);
+        JmxOperationInvoker operationInvoker = new JmxOperationInvoker(memberRmiHostPort.getHost(), memberRmiHostPort.getPort(), userName, passwordToUse, sslConfigProps, gfSecurityPropertiesPath);
         gfshInstance.setOperationInvoker(operationInvoker);
         infoResultData.addLine(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, memberRmiHostPort.toString(false)));
         LogWrapper.getInstance().info(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, memberRmiHostPort.toString(false)));
@@ -599,7 +623,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
   }
 
   // Copied from DistributedSystem.java
-  private static URL getFileUrl(String fileName) {
+  public static URL getFileUrl(String fileName) {
     File file = new File(fileName);
 
     if (file.exists()) {
@@ -657,6 +681,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = { CliStrings.DISCONNECT }, help = CliStrings.DISCONNECT__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_MANAGER})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result disconnect() {
     Result result = null;
 
@@ -689,6 +714,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = {CliStrings.DESCRIBE_CONNECTION}, help = CliStrings.DESCRIBE_CONNECTION__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_JMX})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result describeConnection() {
     Result result = null;
     try {
@@ -716,6 +742,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = { CliStrings.ECHO }, help = CliStrings.ECHO__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result echo(
       @CliOption(key = {CliStrings.ECHO__STR, ""},
                  unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
@@ -753,6 +780,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = { CliStrings.SET_VARIABLE }, help = CliStrings.SET_VARIABLE__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result setVariable(
       @CliOption(key = CliStrings.SET_VARIABLE__VAR,
                  mandatory=true,
@@ -792,6 +820,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = { CliStrings.DEBUG }, help = CliStrings.DEBUG__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL })
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result debug(
       @CliOption(key = CliStrings.DEBUG__STATE,
                    unspecifiedDefaultValue = "OFF",
@@ -821,6 +850,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = CliStrings.HISTORY, help = CliStrings.HISTORY__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GFSH })
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result history(
       @CliOption(key = { CliStrings.HISTORY__FILE }, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.HISTORY__FILE__HELP)
       String saveHistoryTo,
@@ -932,6 +962,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = { CliStrings.RUN }, help = CliStrings.RUN__HELP)
   @CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result executeScript(
       @CliOption(key = CliStrings.RUN__FILE,
                  optionContext = ConverterHint.FILE,
@@ -963,6 +994,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = CliStrings.ENCRYPT, help = CliStrings.ENCRYPT__HELP)
   @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result encryptPassword(
       @CliOption(key = CliStrings.ENCRYPT_STRING,
                  help = CliStrings.ENCRYPT_STRING__HELP,
@@ -973,6 +1005,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = { CliStrings.VERSION }, help = CliStrings.VERSION__HELP)
   @CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result version(
       @CliOption(key = { CliStrings.VERSION__FULL },
                  specifiedDefaultValue = "true",
@@ -986,6 +1019,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = { CliStrings.SLEEP }, help = CliStrings.SLEEP__HELP)
   @CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result sleep(
       @CliOption(key = { CliStrings.SLEEP__TIME },
                  unspecifiedDefaultValue = "3",
@@ -1000,6 +1034,7 @@ private void configureHttpsURLConnection(Map<String, String> sslConfigProps) thr
 
   @CliCommand(value = { CliStrings.SH }, help = CliStrings.SH__HELP)
   @CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result sh(
       @CliArgument(name = CliStrings.SH__COMMAND,
                    mandatory = true,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/StatusCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/StatusCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/StatusCommands.java
index 5abd08a..b7f4094 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/StatusCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/StatusCommands.java
@@ -28,6 +28,9 @@ import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.configuration.domain.SharedConfigurationStatus;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /********
  * 
@@ -41,6 +44,7 @@ public class StatusCommands extends AbstractCommandsSupport implements CommandMa
   @SuppressWarnings("unchecked")
   @CliCommand (value = CliStrings.STATUS_SHARED_CONFIG, help = CliStrings.STATUS_SHARED_CONFIG_HELP)
   @CliMetaData (relatedTopic = CliStrings.TOPIC_GEMFIRE_LOCATOR)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result statusSharedConfiguration() {
     final GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
     final Set<DistributedMember> locators = new HashSet<DistributedMember>(cache.getDistributionManager().getAllHostedLocatorsWithSharedConfiguration().keySet());

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/WanCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/WanCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/WanCommands.java
index a6d9abf..4fa9788 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/WanCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/WanCommands.java
@@ -58,6 +58,9 @@ import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
 import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 public class WanCommands implements CommandMarker {
 
@@ -67,6 +70,7 @@ public class WanCommands implements CommandMarker {
   
   @CliCommand(value = CliStrings.CREATE_GATEWAYSENDER, help = CliStrings.CREATE_GATEWAYSENDER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN, writesToSharedConfiguration=true)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.CREATE_GW_SENDER)
   public Result createGatewaySender(
       @CliOption(key = CliStrings.CREATE_GATEWAYSENDER__GROUP,
       optionContext = ConverterHint.MEMBERGROUP,
@@ -183,6 +187,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.START_GATEWAYSENDER, help = CliStrings.START_GATEWAYSENDER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.GATEWAY_SENDER, operation=ResourceConstants.START_GW_SENDER)
   public Result startGatewaySender(
       @CliOption(key = CliStrings.START_GATEWAYSENDER__ID, 
       mandatory = true, 
@@ -325,6 +330,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.PAUSE_GATEWAYSENDER, help = CliStrings.PAUSE_GATEWAYSENDER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.GATEWAY_SENDER, operation=ResourceConstants.PAUSE_GW_SENDER)
   public Result pauseGatewaySender(
       @CliOption(key = CliStrings.PAUSE_GATEWAYSENDER__ID, 
       mandatory = true, 
@@ -417,6 +423,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.RESUME_GATEWAYSENDER, help = CliStrings.RESUME_GATEWAYSENDER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.GATEWAY_SENDER, operation=ResourceConstants.RESUME_GW_SENDER)
   public Result resumeGatewaySender(
       @CliOption(key = CliStrings.RESUME_GATEWAYSENDER__ID, 
       mandatory = true, 
@@ -556,6 +563,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.STOP_GATEWAYSENDER, help = CliStrings.STOP_GATEWAYSENDER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.GATEWAY_SENDER, operation=ResourceConstants.STOP_GW_SENDER)
   public Result stopGatewaySender(
       @CliOption(key = CliStrings.STOP_GATEWAYSENDER__ID, 
       mandatory = true, 
@@ -631,6 +639,7 @@ public class WanCommands implements CommandMarker {
   
   @CliCommand(value = CliStrings.CREATE_GATEWAYRECEIVER, help = CliStrings.CREATE_GATEWAYRECEIVER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.CREATE_GW_RECEIVER)
   public Result createGatewayReceiver(
       @CliOption(key = CliStrings.CREATE_GATEWAYRECEIVER__GROUP,
       optionContext = ConverterHint.MEMBERGROUP,
@@ -710,6 +719,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.LOAD_BALANCE_GATEWAYSENDER, help = CliStrings.LOAD_BALANCE_GATEWAYSENDER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LOAD_BALANCE_GW_SENDER)
   public Result loadBalanceGatewaySender(
       @CliOption(key = CliStrings.LOAD_BALANCE_GATEWAYSENDER__ID, 
       mandatory = true, 
@@ -775,6 +785,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.START_GATEWAYRECEIVER, help = CliStrings.START_GATEWAYRECEIVER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.GATEWAY_RECEIVER, operation=ResourceConstants.START_GW_RECEIVER)
   public Result startGatewayReceiver(
       @CliOption(key = CliStrings.START_GATEWAYRECEIVER__GROUP,
       optionContext = ConverterHint.MEMBERGROUP,
@@ -836,6 +847,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.STOP_GATEWAYRECEIVER, help = CliStrings.STOP_GATEWAYRECEIVER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.GATEWAY_RECEIVER, operation=ResourceConstants.STOP_GW_RECEIVER)
   public Result stopGatewayReceiver(
       
       @CliOption(key = CliStrings.STOP_GATEWAYRECEIVER__GROUP, 
@@ -909,6 +921,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.LIST_GATEWAY, help = CliStrings.LIST_GATEWAY__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result listGateway(
       @CliOption(key = CliStrings.LIST_GATEWAY__MEMBER,
       optionContext = ConverterHint.MEMBERIDNAME,
@@ -999,6 +1012,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.STATUS_GATEWAYSENDER, help = CliStrings.STATUS_GATEWAYSENDER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result statusGatewaySender(
       @CliOption(key = CliStrings.STATUS_GATEWAYSENDER__ID, 
       mandatory = true, 
@@ -1065,6 +1079,7 @@ public class WanCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.STATUS_GATEWAYRECEIVER, help = CliStrings.STATUS_GATEWAYRECEIVER__HELP)
   @CliMetaData(relatedTopic = CliStrings.TOPIC_GEMFIRE_WAN)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public Result statusGatewayReceiver(
       @CliOption(key = CliStrings.STATUS_GATEWAYRECEIVER__GROUP, 
       optionContext = ConverterHint.MEMBERGROUP,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/shell/JmxOperationInvoker.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/shell/JmxOperationInvoker.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/shell/JmxOperationInvoker.java
index 864907b..761651e 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/shell/JmxOperationInvoker.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/shell/JmxOperationInvoker.java
@@ -8,17 +8,22 @@
  */
 package com.gemstone.gemfire.management.internal.cli.shell;
 
+import java.io.File;
 import java.io.IOException;
+import java.io.InputStream;
 import java.net.MalformedURLException;
+import java.net.URL;
 import java.text.MessageFormat;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.Properties;
 import java.util.Set;
 import java.util.TreeSet;
 import java.util.concurrent.atomic.AtomicBoolean;
+
 import javax.management.AttributeNotFoundException;
 import javax.management.InstanceNotFoundException;
 import javax.management.JMX;
@@ -36,13 +41,18 @@ import javax.management.remote.JMXConnectorFactory;
 import javax.management.remote.JMXServiceURL;
 import javax.rmi.ssl.SslRMIClientSocketFactory;
 
+import com.gemstone.gemfire.internal.lang.StringUtils;
 import com.gemstone.gemfire.internal.util.ArrayUtils;
+import com.gemstone.gemfire.internal.util.IOUtils;
 import com.gemstone.gemfire.management.DistributedSystemMXBean;
 import com.gemstone.gemfire.management.MemberMXBean;
 import com.gemstone.gemfire.management.internal.MBeanJMXAdapter;
 import com.gemstone.gemfire.management.internal.ManagementConstants;
+import com.gemstone.gemfire.management.internal.cli.CliUtil;
 import com.gemstone.gemfire.management.internal.cli.CommandRequest;
 import com.gemstone.gemfire.management.internal.cli.LogWrapper;
+import com.gemstone.gemfire.management.internal.cli.commands.ShellCommands;
+import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 
 /**
  * OperationInvoker JMX Implementation
@@ -86,7 +96,7 @@ public class JmxOperationInvoker implements OperationInvoker {
                              final int port,
                              final String userName,
                              final String password,
-                             final Map<String, String> sslConfigProps)
+                             final Map<String, String> sslConfigProps, String gfSecurityPropertiesPath)
     throws Exception
   {
     final Set<String> propsToClear = new TreeSet<String>();
@@ -123,6 +133,11 @@ public class JmxOperationInvoker implements OperationInvoker {
         }
       }
 
+      //Check for JMX Credentials if empty put properties instance directly so that
+      //jmx management interceptor can read it for custom security properties
+      if(!env.containsKey(JMXConnector.CREDENTIALS)) {        
+        env.put(JMXConnector.CREDENTIALS, readProperties(gfSecurityPropertiesPath));
+      }
 
       this.url = new JMXServiceURL(MessageFormat.format(JMX_URL_FORMAT, checkAndConvertToCompatibleIPv6Syntax(host), String.valueOf(port)));      
       this.connector = JMXConnectorFactory.connect(url, env);
@@ -167,6 +182,53 @@ public class JmxOperationInvoker implements OperationInvoker {
     }
   }
 
+  //Copied from ShellCommands.java
+  private Properties readProperties(String gfSecurityPropertiesPath) throws MalformedURLException {
+    Gfsh gfshInstance = Gfsh.getCurrentInstance();
+    // reference to hold resolved gfSecurityPropertiesPath
+    String gfSecurityPropertiesPathToUse = CliUtil.resolvePathname(gfSecurityPropertiesPath);
+    URL gfSecurityPropertiesUrl = null;
+
+    // Case 1: User has specified gfSecurity properties file
+    if (!StringUtils.isBlank(gfSecurityPropertiesPathToUse)) {
+      // User specified gfSecurity properties doesn't exist
+      if (!IOUtils.isExistingPathname(gfSecurityPropertiesPathToUse)) {
+        gfshInstance.printAsSevere(CliStrings.format(CliStrings.GEMFIRE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ", gfSecurityPropertiesPathToUse));
+      } else {
+        gfSecurityPropertiesUrl = new File(gfSecurityPropertiesPathToUse).toURI().toURL();
+      }
+    } else if (gfSecurityPropertiesPath == null) {
+      // Use default "gfsecurity.properties"
+      // in current dir, user's home or classpath
+      gfSecurityPropertiesUrl = ShellCommands.getFileUrl("gfsecurity.properties");
+    }
+    // if 'gfSecurityPropertiesPath' OR gfsecurity.properties has resolvable path
+    if (gfSecurityPropertiesUrl != null) {
+      gfshInstance.logToFile("Using security properties file : "
+              + CliUtil.decodeWithDefaultCharSet(gfSecurityPropertiesUrl.getPath()), null);
+      return loadPropertiesFromURL(gfSecurityPropertiesUrl);      
+    }  
+    return null;
+  }
+  
+  static Properties loadPropertiesFromURL(URL gfSecurityPropertiesUrl) {
+    Properties props = new Properties();
+    if (gfSecurityPropertiesUrl != null) {
+      InputStream inputStream = null;
+      try {
+        
+        inputStream = gfSecurityPropertiesUrl.openStream();
+        props.load(inputStream);
+      } catch (IOException io) {
+        throw new RuntimeException(CliStrings.format(
+            CliStrings.CONNECT__MSG__COULD_NOT_READ_CONFIG_FROM_0,
+                CliUtil.decodeWithDefaultCharSet(gfSecurityPropertiesUrl.getPath())), io);
+      } finally {
+        IOUtils.close(inputStream);
+      }
+    }
+    return props;
+  }
   
   private String checkforSystemPropertyPrefix(String key) {
     String returnKey = key;

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControl.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControl.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControl.java
index 58040cd..edbec7f 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControl.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControl.java
@@ -8,6 +8,13 @@ import java.util.Set;
 import javax.management.remote.JMXPrincipal;
 import javax.security.auth.Subject;
 
+/**
+ * AccessControlMBean Implementation. This retrieves JMXPrincipal from AccessController
+ * and performs authorization for given role using gemfire AccessControl Plugin
+ *  
+ * @author tushark
+ * @since 9.0
+ */
 public class AccessControl implements AccessControlMXBean {
 
   private ManagementInterceptor interceptor;
@@ -20,13 +27,12 @@ public class AccessControl implements AccessControlMXBean {
   public boolean authorize(String role) {
     AccessControlContext acc = AccessController.getContext();
     Subject subject = Subject.getSubject(acc);
-    Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class);
-    Set<Object> pubCredentials = subject.getPublicCredentials();
+    Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class);    
     if (principals == null || principals.isEmpty()) {
       throw new SecurityException("Access denied");
     }
     Principal principal = principals.iterator().next();
-    com.gemstone.gemfire.security.AccessControl gemAccControl = interceptor.getAccessControl(principal);
+    com.gemstone.gemfire.security.AccessControl gemAccControl = interceptor.getAccessControl(principal, false);
     boolean authorized = gemAccControl.authorizeOperation(null,
         new com.gemstone.gemfire.management.internal.security.AccessControlContext(role));
     return authorized;

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlContext.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlContext.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlContext.java
index 1926db5..e44dc18 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlContext.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlContext.java
@@ -1,5 +1,14 @@
 package com.gemstone.gemfire.management.internal.security;
 
+/**
+ * 
+ * ResourceOperationContext passed to AccessControlMBean for Authorization calls made
+ * from AccessControlMBean
+ * 
+ * @author tushark
+ * @since 9.0
+ *
+ */
 public class AccessControlContext extends ResourceOperationContext {
   
   private ResourceOperationCode code;
@@ -16,6 +25,9 @@ public class AccessControlContext extends ResourceOperationContext {
   @Override
   public OperationCode getOperationCode() {   
     return OperationCode.RESOURCE;
-  }  
+  }
+  
+  public static AccessControlContext ACCESS_GRANTED_CONTEXT = new AccessControlContext(ResourceConstants.LIST_DS);
 
 }
+

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlMXBean.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlMXBean.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlMXBean.java
index e217045..acd0ca3 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlMXBean.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/AccessControlMXBean.java
@@ -1,7 +1,13 @@
 package com.gemstone.gemfire.management.internal.security;
 
+/**
+ * Interface for AccessControlMBean
+ * @author tushark
+ * @since 9.0
+ */
 public interface AccessControlMXBean {
 
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.LIST_DS)
   public boolean authorize(String role);
   
 }


[2/6] incubator-geode git commit: GEODE-77 : Integrated Security Code Merge Review board url : https://reviews.apache.org/r/37209/

Posted by tu...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/security/TokenService.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/security/TokenService.java b/gemfire-core/src/main/java/com/gemstone/gemfire/security/TokenService.java
new file mode 100644
index 0000000..4a397ba
--- /dev/null
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/security/TokenService.java
@@ -0,0 +1,60 @@
+/**
+ * 
+ */
+package com.gemstone.gemfire.security;
+
+import java.security.Principal;
+
+/**
+ * This interface provides APIs to generate and validate tokens for Geode REST
+ * clients.
+ * <p>
+ * A single instance of the implementing class per cache will created by Geode
+ * and these methods will be invoked on that same instance. Synchronization, if
+ * any, needs to be handled by the implementation itself.
+ */
+public interface TokenService {
+
+  /**
+   * Generates an unique token for the given principal. Geode REST service keeps
+   * track of each token and its associated client and only validates this token
+   * for each subsequent request from the same REST client, thus eliminating the
+   * need to explicitly authenticate it every time.
+   * 
+   * <p>
+   * If a REST client sends its credentials in its subsequent requests, instead
+   * of the issued token, the Geode REST service treats it as a new client's
+   * request and issues a new token for it.
+   * 
+   * @param principal
+   *          the principal which the token is to be generated for.
+   * @return the generated token for the given principal.
+   */
+  public String generateToken(Principal principal);
+
+  /**
+   * Verifies that the provided token is a valid one for the provided principal.
+   * Optionally, it may replace this token by returning a new one. Thus, a new
+   * token is exchanged for each request from the client.
+   * 
+   * <p>
+   * The REST client must send this returned token in its next request instead
+   * of the credentials. The method throws appropriate authentication exception
+   * if the token is not valid.
+   * <p>
+   * The implementation may expire the tokens after regular interval so as to
+   * minimise its possible misuse.
+   * 
+   * @param token
+   *          the token to be validated. This is the token the client had
+   *          received in the previous response from the Geode REST service and
+   *          has sent it back in its current request to the Geode REST service.
+   * @param principal
+   *          the principal associated with the given token.
+   * @return the validated token. The implementation may also issue a new token
+   *         replacing earlier one for the client.
+   */
+  public String validateToken(String token, Principal principal)
+      throws AuthenticationRequiredException, AuthenticationFailedException;
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/extension/mock/MockExtensionCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/extension/mock/MockExtensionCommands.java b/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/extension/mock/MockExtensionCommands.java
index 89644f0..5e1f26d 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/extension/mock/MockExtensionCommands.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/extension/mock/MockExtensionCommands.java
@@ -30,6 +30,9 @@ import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
 import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * Mock Extension gfsh commands.
@@ -70,6 +73,7 @@ public class MockExtensionCommands implements CommandMarker {
    */
   @CliCommand(value = CREATE_MOCK_REGION_EXTENSION)
   @CliMetaData(writesToSharedConfiguration = true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result createMockRegionExtension(@CliOption(key = OPTION_REGION_NAME, mandatory = true) final String regionName,
       @CliOption(key = OPTION_VALUE, mandatory = true) final String value) {
     return executeFunctionOnAllMembersTabulateResultPersist(CreateMockRegionExtensionFunction.INSTANCE, true,
@@ -90,6 +94,7 @@ public class MockExtensionCommands implements CommandMarker {
    */
   @CliCommand(value = ALTER_MOCK_REGION_EXTENSION)
   @CliMetaData(writesToSharedConfiguration = true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result alterMockRegionExtension(@CliOption(key = OPTION_REGION_NAME, mandatory = true) final String regionName,
       @CliOption(key = OPTION_VALUE, mandatory = true) final String value) {
     return executeFunctionOnAllMembersTabulateResultPersist(AlterMockRegionExtensionFunction.INSTANCE, true,
@@ -108,6 +113,7 @@ public class MockExtensionCommands implements CommandMarker {
    */
   @CliCommand(value = DESTROY_MOCK_REGION_EXTENSION)
   @CliMetaData(writesToSharedConfiguration = true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result destroyMockRegionExtension(@CliOption(key = OPTION_REGION_NAME, mandatory = true) final String regionName) {
     return executeFunctionOnAllMembersTabulateResultPersist(DestroyMockRegionExtensionFunction.INSTANCE, true,
         DestroyMockRegionExtensionFunction.toArgs(regionName));
@@ -124,6 +130,7 @@ public class MockExtensionCommands implements CommandMarker {
    */
   @CliCommand(value = CREATE_MOCK_CACHE_EXTENSION)
   @CliMetaData(writesToSharedConfiguration = true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result createMockCacheExtension(@CliOption(key = OPTION_VALUE, mandatory = true) final String value) {
     return executeFunctionOnAllMembersTabulateResultPersist(CreateMockCacheExtensionFunction.INSTANCE, true, CreateMockCacheExtensionFunction.toArgs(value));
   }
@@ -138,6 +145,7 @@ public class MockExtensionCommands implements CommandMarker {
    * @since 8.1
    */
   @CliCommand(value = ALTER_MOCK_CACHE_EXTENSION)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   @CliMetaData(writesToSharedConfiguration = true)
   public Result alterMockCacheExtension(@CliOption(key = OPTION_VALUE, mandatory = true) final String value) {
     return executeFunctionOnAllMembersTabulateResultPersist(AlterMockCacheExtensionFunction.INSTANCE, true, AlterMockCacheExtensionFunction.toArgs(value));
@@ -150,6 +158,7 @@ public class MockExtensionCommands implements CommandMarker {
    * @since 8.1
    */
   @CliCommand(value = DESTROY_MOCK_CACHE_EXTENSION)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   @CliMetaData(writesToSharedConfiguration = true)
   public Result destroyMockCacheExtension() {
     return executeFunctionOnAllMembersTabulateResultPersist(DestroyMockCacheExtensionFunction.INSTANCE, false);

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/CommandManagerJUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/CommandManagerJUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/CommandManagerJUnitTest.java
index ab9333d..dea9d92 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/CommandManagerJUnitTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/CommandManagerJUnitTest.java
@@ -37,8 +37,12 @@ import com.gemstone.gemfire.management.internal.cli.parser.Argument;
 import com.gemstone.gemfire.management.internal.cli.parser.AvailabilityTarget;
 import com.gemstone.gemfire.management.internal.cli.parser.CommandTarget;
 import com.gemstone.gemfire.management.internal.cli.parser.Option;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 import com.gemstone.gemfire.test.junit.categories.UnitTest;
 
+
 /**
  * CommandManagerTest - Includes tests to check the CommandManager functions
  * 
@@ -220,6 +224,7 @@ public class CommandManagerJUnitTest {
   static public class Commands implements CommandMarker {
     @CliCommand(value = { COMMAND1_NAME, COMMAND1_NAME_ALIAS }, help = COMMAND1_HELP)
     @CliMetaData(shellOnly = true, relatedTopic = { "relatedTopicOfCommand1" })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static String command1(
         @CliArgument(name = ARGUMENT1_NAME, argumentContext = ARGUMENT1_CONTEXT, help = ARGUMENT1_HELP, mandatory = true)
         String argument1,
@@ -235,11 +240,13 @@ public class CommandManagerJUnitTest {
     }
 
     @CliCommand(value = { COMMAND2_NAME })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static String command2() {
       return null;
     }
 
     @CliCommand(value = { "testParamConcat" })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static Result testParamConcat(
         @CliOption(key = { "string" })
         String string,
@@ -256,6 +263,7 @@ public class CommandManagerJUnitTest {
     }
 
     @CliCommand(value = { "testMultiWordArg" })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static Result testMultiWordArg(@CliArgument(name = "arg1")
     String arg1, @CliArgument(name = "arg2")
     String arg2) {
@@ -306,6 +314,7 @@ public class CommandManagerJUnitTest {
 
   public static class MockPluginCommand implements CommandMarker {
     @CliCommand(value = "mock plugin command")
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public Result mockPluginCommand() {
       return null;
     }
@@ -313,6 +322,7 @@ public class CommandManagerJUnitTest {
 
   public static class MockPluginCommandUnlisted implements CommandMarker {
     @CliCommand(value = "mock plugin command unlisted")
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public Result mockPluginCommandUnlisted() {
       return null;
     }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/GfshParserJUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/GfshParserJUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/GfshParserJUnitTest.java
index 126bb88..4a0a431 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/GfshParserJUnitTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/GfshParserJUnitTest.java
@@ -38,6 +38,9 @@ import com.gemstone.gemfire.management.internal.cli.converters.StringListConvert
 import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 import com.gemstone.gemfire.management.internal.cli.parser.SyntaxConstants;
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 import com.gemstone.gemfire.test.junit.categories.UnitTest;
 
 /**
@@ -1042,6 +1045,7 @@ public class GfshParserJUnitTest {
   static class Commands implements CommandMarker {
 
     @CliCommand(value = { COMMAND1_NAME, COMMAND1_NAME_ALIAS }, help = COMMAND1_HELP)
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static String command1(
         @CliArgument(name = ARGUMENT1_NAME, argumentContext = ARGUMENT1_CONTEXT, help = ARGUMENT1_HELP, mandatory = true)
         String argument1,
@@ -1057,11 +1061,13 @@ public class GfshParserJUnitTest {
     }
 
     @CliCommand(value = { COMMAND2_NAME })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static String command2() {
       return null;
     }
 
     @CliCommand(value = { "testParamConcat" })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static Result testParamConcat(
         @CliOption(key = { "string" }) String string,
         @CliOption(key = { "stringArray" }) @CliMetaData(valueSeparator = ",") String[] stringArray,
@@ -1072,6 +1078,7 @@ public class GfshParserJUnitTest {
     }
 
     @CliCommand(value = { "testMultiWordArg" })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static Result testMultiWordArg(
         @CliArgument(name = "arg1" ) String arg1,
         @CliArgument(name = "arg2" ) String arg2) {
@@ -1128,17 +1135,18 @@ public class GfshParserJUnitTest {
     static final String C2_MSG_AVAILABLE   = C2_NAME + " is available.";
 
     @CliCommand(value = { C1_NAME })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public Result command1() {
       return ResultBuilder.createInfoResult(C1_MSG_AVAILABLE);
     }
 
     @CliCommand(value = { C2_NAME })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public Result command2() {
       return ResultBuilder.createInfoResult(C2_MSG_AVAILABLE);
     }
 
-    @CliAvailabilityIndicator(C1_NAME)
-    @CliMetaData.AvailabilityMetadata(availabilityDescription=C1_MSG_UNAVAILABLE)
+    @CliAvailabilityIndicator(C1_NAME)    
     public boolean isCommand1Available() {
       return Boolean.getBoolean(C1_PROP);
     }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/shell/GfshExecutionStrategyJUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/shell/GfshExecutionStrategyJUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/shell/GfshExecutionStrategyJUnitTest.java
index 44aef44..659b407 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/shell/GfshExecutionStrategyJUnitTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/shell/GfshExecutionStrategyJUnitTest.java
@@ -29,6 +29,9 @@ import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
 import com.gemstone.gemfire.management.internal.cli.shell.GfshConfig;
 import com.gemstone.gemfire.management.internal.cli.shell.GfshExecutionStrategy;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 import com.gemstone.gemfire.test.junit.categories.UnitTest;
 
 /**
@@ -92,17 +95,20 @@ public class GfshExecutionStrategyJUnitTest {
 
     @CliCommand(value = { COMMAND1_NAME, COMMAND1_NAME_ALIAS }, help = COMMAND1_HELP)
     @CliMetaData(shellOnly = true )
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static Result command1() {     
       return ResultBuilder.createInfoResult(COMMAND1_SUCESS);      
     }
 
     @CliCommand(value = { COMMAND2_NAME })
     @CliMetaData(shellOnly = false )
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static Result command2() {
       return ResultBuilder.createInfoResult(COMMAND2_SUCESS);      
     }
 
     @CliCommand(value = { "testParamConcat" })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static Result testParamConcat(
         @CliOption(key = { "string" })
         String string,
@@ -119,6 +125,7 @@ public class GfshExecutionStrategyJUnitTest {
     }
 
     @CliCommand(value = { "testMultiWordArg" })
+    @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
     public static Result testMultiWordArg(@CliArgument(name = "arg1")
     String arg1, @CliArgument(name = "arg2")
     String arg2) {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/JSONAuthCodeTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/JSONAuthCodeTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/JSONAuthCodeTest.java
index 384493b..fa9a292 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/JSONAuthCodeTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/JSONAuthCodeTest.java
@@ -173,7 +173,7 @@ public class JSONAuthCodeTest extends TestCase {
   }
 
   private void checkAccessControlMBean() throws Exception {
-    ObjectName name = new ObjectName(ManagementInterceptor.OBJECT_NAME_ACCESSCONTROL);
+    ObjectName name = new ObjectName(ResourceConstants.OBJECT_NAME_ACCESSCONTROL);
     MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
     Set<ObjectName> names = platformMBeanServer.queryNames(name, null);
     assertFalse(names.isEmpty());

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/ResourceOperationJUnit.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/ResourceOperationJUnit.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/ResourceOperationJUnit.java
index f061240..b88b56c 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/ResourceOperationJUnit.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/security/ResourceOperationJUnit.java
@@ -2,26 +2,37 @@ package com.gemstone.gemfire.management.internal.security;
 
 import java.io.IOException;
 import java.io.Serializable;
+import java.lang.annotation.Annotation;
 import java.net.MalformedURLException;
 import java.security.Principal;
+import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
 
+import javax.management.Attribute;
+import javax.management.AttributeList;
 import javax.management.AttributeNotFoundException;
 import javax.management.InstanceNotFoundException;
 import javax.management.JMX;
 import javax.management.MBeanException;
 import javax.management.MBeanServerConnection;
 import javax.management.MalformedObjectNameException;
+import javax.management.ObjectInstance;
 import javax.management.ObjectName;
 import javax.management.ReflectionException;
 import javax.management.remote.JMXConnector;
 import javax.management.remote.JMXConnectorFactory;
 import javax.management.remote.JMXServiceURL;
 
+
+
 import org.junit.experimental.categories.Category;
 
+
 import junit.framework.TestCase;
 
 import com.gemstone.gemfire.LogWriter;
@@ -33,10 +44,15 @@ import com.gemstone.gemfire.distributed.DistributedMember;
 import com.gemstone.gemfire.distributed.DistributedSystem;
 import com.gemstone.gemfire.distributed.internal.DistributionConfig;
 import com.gemstone.gemfire.internal.AvailablePort;
+import com.gemstone.gemfire.internal.AvailablePortHelper;
 import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+import com.gemstone.gemfire.internal.logging.LogService;
 import com.gemstone.gemfire.management.DistributedSystemMXBean;
 import com.gemstone.gemfire.management.MemberMXBean;
 import com.gemstone.gemfire.management.internal.MBeanJMXAdapter;
+import com.gemstone.gemfire.management.internal.cli.CommandManager;
+import com.gemstone.gemfire.management.internal.cli.parser.CommandTarget;
+import com.gemstone.gemfire.management.internal.cli.parser.GfshMethodTarget;
 import com.gemstone.gemfire.management.internal.security.ResourceOperationContext.ResourceOperationCode;
 import com.gemstone.gemfire.security.AccessControl;
 import com.gemstone.gemfire.security.AuthenticationFailedException;
@@ -46,246 +62,457 @@ import com.gemstone.gemfire.test.junit.categories.UnitTest;
 
 @Category(UnitTest.class)
 public class ResourceOperationJUnit  extends TestCase {
-	
-	public static class TestUsernamePrincipal implements Principal,
-			Serializable {
-
-		private final String userName;
-
-		public TestUsernamePrincipal(String userName) {
-			this.userName = userName;
-		}
-
-		public String getName() {
-			return this.userName;
-		}
-
-		@Override
-		public String toString() {
-			return this.userName;
-		}
-
-	}
-
-	public static class TestAuthenticator implements Authenticator {
-
-		@Override
-		public void close() {
-
-		}
-
-		@Override
-		public void init(Properties securityProps, LogWriter systemLogger,
-				LogWriter securityLogger) throws AuthenticationFailedException {
-
-		}
-
-		@Override
-		public Principal authenticate(Properties props, DistributedMember member)
-				throws AuthenticationFailedException {
-			String user = props.getProperty(ManagementInterceptor.USER_NAME);
-			String pwd = props.getProperty(ManagementInterceptor.PASSWORD);
-			if (user!=null && !user.equals(pwd) && !"".equals(user))
-				throw new AuthenticationFailedException(
-						"Wrong username/password");
-			System.out.println("Authentication successful!! for " + user);
-			return new TestUsernamePrincipal(user);
-		}
-
-	}
-	
-	public static class TestAccessControl implements AccessControl {
-
-		private Principal principal=null;
-		@Override
-		public void close() {
-			
-		}
-
-		@Override
-		public void init(Principal principal, DistributedMember remoteMember,
-				Cache cache) throws NotAuthorizedException {
-			this.principal = principal;
-		}
-
-		@Override
-		public boolean authorizeOperation(String regionName,
-				OperationContext context) {
-			if(principal.getName().equals("tushark")) {				
-				ResourceOperationCode authorizedOps[] = {
-						ResourceOperationCode.LIST_DS,
-						ResourceOperationCode.READ_DS,
-						ResourceOperationCode.CHANGE_ALERT_LEVEL_DS,
-						ResourceOperationCode.LOCATE_ENTRY_REGION
-				};
-				
-				System.out.println("Context received " + context);
-				
-				//if(context instanceof JMXOperationContext) {
-					ResourceOperationContext ctx = (ResourceOperationContext)context;
-					System.out.println("Checking for code " + ctx.getResourceOperationCode());
-					boolean found = false;
-					for(ResourceOperationCode code : authorizedOps) {
-						if(ctx.getResourceOperationCode().equals(code)){
-							found =true;
-							System.out.println("found code " + code.toString());
-							break;
-						}							
-					}
-					if(found)
-						return true;
-					System.out.println("Did not find code " + ctx.getResourceOperationCode());
-					return false;
-				//}
-			}			
-			return false;
-		}
-		
-	}
-	
-	public void testJMXOperationContext() {		
-		System.setProperty("resource-auth-accessor", "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl");
-		System.setProperty("resource-authenticator", "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAuthenticator");
-		GemFireCacheImpl cache = null;
-		DistributedSystem ds = null;
-		Properties pr = new Properties();
-		pr.put("name", "testJMXOperationContext");
-		pr.put(DistributionConfig.JMX_MANAGER_NAME, "true");
-		pr.put(DistributionConfig.JMX_MANAGER_START_NAME, "true");
-		int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-		pr.put(DistributionConfig.JMX_MANAGER_PORT_NAME, String.valueOf(port));
-		pr.put(DistributionConfig.HTTP_SERVICE_PORT_NAME, "0");
-		ds = getSystem(pr);
-		cache = (GemFireCacheImpl) CacheFactory.create(ds);
-		ObjectName name = MBeanJMXAdapter.getDistributedSystemName();
-		
-		String[] methods = {
-				"listCacheServerObjectNames",
-				"viewRemoteClusterStatus",
-				"getTotalHeapSize",
-				"setQueryCollectionsDepth",
-				"getQueryCollectionsDepth",
-				"changeAlertLevel",
-				"backupAllMembers",
-				"revokeMissingDiskStores",
-				"shutDownAllMembers",
-				"queryData",
-				"queryDataForCompressedResult",
-				"setQueryResultSetLimit",				
-		};
-		
-		ResourceOperationCode expectedCodes[] = {
-				ResourceOperationCode.LIST_DS,
-				ResourceOperationCode.LIST_DS,
-				ResourceOperationCode.READ_DS,
-				ResourceOperationCode.QUERYDATA_DS,
-				ResourceOperationCode.READ_DS,
-				ResourceOperationCode.CHANGE_ALERT_LEVEL_DS,
-				ResourceOperationCode.BACKUP_DS,
-				ResourceOperationCode.REMOVE_DISKSTORE_DS,
-				ResourceOperationCode.SHUTDOWN_DS,
-				ResourceOperationCode.QUERYDATA_DS,
-				ResourceOperationCode.QUERYDATA_DS,
-				ResourceOperationCode.QUERYDATA_DS
-		};
-				
-		for(int i=0;i<methods.length;i++) {
-			String methodName = methods[i];
-			JMXOperationContext context = new JMXOperationContext(name, methodName);
-			assertEquals(expectedCodes[i],
-					context.getResourceOperationCode());
-			assertEquals(OperationCode.RESOURCE, context.getOperationCode());
-		}
-		
-		JMXConnector cs = getGemfireMBeanServer(port, "tushark", "tushark");;
-		MBeanServerConnection mbeanServer =null;
-		try {
-			mbeanServer = cs.getMBeanServerConnection();
-			mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(), "listCacheServerObjectNames", null, null);
-			String oldLevel = (String)mbeanServer.getAttribute(MBeanJMXAdapter.getDistributedSystemName(), "AlertLevel");
-			System.out.println("Old Level = " + oldLevel);
-			mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(), "changeAlertLevel", new Object[]{"WARNING"},new String[]{
-				String.class.getCanonicalName()
-			});
-			String newLevel = (String)mbeanServer.getAttribute(MBeanJMXAdapter.getDistributedSystemName(), "AlertLevel");
-			System.out.println("New Level = " + newLevel);
-			
-			
-			//Checking accessControlMXBean
-			System.out.println("Checking access via AccessControlMbean");			
-			ResourceOperationCode authorizedOps[] = {
-          ResourceOperationCode.LIST_DS,
-          ResourceOperationCode.READ_DS,
-          ResourceOperationCode.CHANGE_ALERT_LEVEL_DS,
-          ResourceOperationCode.LOCATE_ENTRY_REGION
-      };
-			ObjectName accControlON = new ObjectName(ManagementInterceptor.OBJECT_NAME_ACCESSCONTROL);
-			for(ResourceOperationCode c : authorizedOps) {
-			  boolean result = (Boolean) mbeanServer.invoke(accControlON, "authorize"
-	          , new Object[]{ResourceOperationCode.CHANGE_ALERT_LEVEL_DS.toString()}
-	          , new String[]{String.class.getCanonicalName()}); 
-	      assertTrue(result);
-			}
-			
-			boolean result = (Boolean) mbeanServer.invoke(accControlON, "authorize"
-          , new Object[]{ResourceOperationCode.ADMIN_DS.toString()}
-          , new String[]{String.class.getCanonicalName()}); 
-      assertFalse(result);			
-			
-		} catch (InstanceNotFoundException e1) {
-		  e1.printStackTrace();
-			fail("Error while invoking JMXRMI " + e1.getMessage());
-		} catch (MBeanException e1) {
-		  e1.printStackTrace();
-			fail("Error while invoking JMXRMI " + e1.getMessage());
-		} catch (ReflectionException e1) {
-			fail("Error while invoking JMXRMI " + e1.getMessage());
-		} catch (IOException e1) {
-			fail("Error while invoking JMXRMI " + e1.getMessage());
-		} catch (AttributeNotFoundException e) {
-			fail("Error while invoking JMXRMI" + e.getMessage());
-		} catch (MalformedObjectNameException e) {
-		  fail("Error while invoking JMXRMI" + e.getMessage());
+  
+  public static class TestUsernamePrincipal implements Principal,
+      Serializable {
+
+    private final String userName;
+
+    public TestUsernamePrincipal(String userName) {
+      this.userName = userName;
+    }
+
+    public String getName() {
+      return this.userName;
+    }
+
+    @Override
+    public String toString() {
+      return this.userName;
+    }
+
+  }
+
+  public static class TestAuthenticator implements Authenticator {
+
+    @Override
+    public void close() {
+
+    }
+
+    @Override
+    public void init(Properties securityProps, LogWriter systemLogger,
+        LogWriter securityLogger) throws AuthenticationFailedException {
+
+    }
+
+    @Override
+    public Principal authenticate(Properties props, DistributedMember member)
+ throws AuthenticationFailedException {
+      String mysecret = props.getProperty("GoTSecret");
+      props.list(System.out);
+      if (mysecret == null) {
+        String user = props.getProperty(ResourceConstants.USER_NAME);
+        String pwd = props.getProperty(ResourceConstants.PASSWORD);
+        if (user != null && !user.equals(pwd) && !"".equals(user))
+          throw new AuthenticationFailedException("Wrong username/password");
+        System.out.println("Authentication successful!! for " + user);
+        return new TestUsernamePrincipal(user);
+      } else {
+        if (mysecret.equals("JohnSnowIsIceAndFire")) {
+          System.out.println("Authentication successful!! for IronThrone");
+          return new TestUsernamePrincipal("IronThrone");
+        } else
+          throw new AuthenticationFailedException("Wrong username/password");
+      }
+    }
+    
+    public static Authenticator create() {
+      return new TestAuthenticator();
+    }
+
+  }
+  
+  public static class TestAccessControl implements AccessControl {
+
+    private Principal principal=null;   
+    public static AtomicInteger preCallsTL = new AtomicInteger(0);
+    public static AtomicInteger postCallsTL = new AtomicInteger(0);
+    
+    public static boolean failPostOpIntentionally = false;
+    
+    public static AccessControl create(){
+      return new TestAccessControl();
+    }
+    
+    static {
+      resetCallsCounter();
+    }
+
+    public static void resetCallsCounter() {      
+      preCallsTL.set(0);
+      postCallsTL.set(0);
+    }
+    
+    @Override
+    public void close() {
+      
+    }
+
+    @Override
+    public void init(Principal principal, DistributedMember remoteMember,
+        Cache cache) throws NotAuthorizedException {
+      this.principal = principal;
+    }
+    
+    private void increaseCount(OperationContext context) {
+      if (!(context instanceof AccessControlContext)) {
+        if (context.isPostOperation()) {
+          postCallsTL.incrementAndGet();
+          System.out.println("Context Received " + context + " isPostOp=" + context.isPostOperation() + " calls="
+              + postCallsTL.get());
+        } else {
+          preCallsTL.incrementAndGet();
+          System.out.println("Context Received " + context + " isPreOp=" + context.isPostOperation() + " calls="
+              + preCallsTL.get());
+        }
+      }     
+    }
+
+    @Override
+    public boolean authorizeOperation(String regionName,
+        OperationContext context) {
+
+      if(context.isPostOperation() && failPostOpIntentionally) {
+        System.out.println("Failing AuthZ since failPostOpIntentionally=true");
+        return false;
+      }
+      
+      if(principal.getName().equals("tushark") || principal.getName().equals("IronThrone")) {       
+        ResourceOperationCode authorizedOps[] = {
+            ResourceOperationCode.LIST_DS,
+            ResourceOperationCode.CHANGE_ALERT_LEVEL,
+            ResourceOperationCode.LOCATE_ENTRY,
+            ResourceOperationCode.QUERY
+        };
+        
+        LogService.getLogger().info("Context received " + context);        
+        ResourceOperationContext ctx = (ResourceOperationContext) context;
+        LogService.getLogger().info("Checking for code " + ctx.getResourceOperationCode());
+        boolean found = false;
+        for (ResourceOperationCode code : authorizedOps) {
+          if (ctx.getResourceOperationCode().equals(code)) {
+            found = true;
+            LogService.getLogger().info("found code " + code.toString());
+            break;
+          }
+        }
+        if (found) {
+          increaseCount(context);
+          return true;
+        }
+        LogService.getLogger().info("Did not find code " + ctx.getResourceOperationCode());        
+        return false;
+      }     
+      return false;
+    }
+    
+  }
+  
+  public void testJMXOperationContext() {   
+    TestAccessControl.resetCallsCounter();    
+    GemFireCacheImpl cache = null;
+    DistributedSystem ds = null;
+    Properties pr = new Properties();
+    pr.put("name", "testJMXOperationContext");
+    pr.put(DistributionConfig.JMX_MANAGER_NAME, "true");
+    pr.put(DistributionConfig.JMX_MANAGER_START_NAME, "true");
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    pr.put(DistributionConfig.JMX_MANAGER_PORT_NAME, String.valueOf(port));
+    pr.put(DistributionConfig.HTTP_SERVICE_PORT_NAME, "0");
+    
+    pr.put(DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAuthenticator.create");
+    pr.put(DistributionConfig.SECURITY_CLIENT_ACCESSOR_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl.create");
+    pr.put(DistributionConfig.SECURITY_CLIENT_ACCESSOR_PP_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl.create");
+    
+    ds = getSystem(pr);
+    cache = (GemFireCacheImpl) CacheFactory.create(ds);
+    ObjectName name = MBeanJMXAdapter.getDistributedSystemName();
+    
+    String[] methods = {
+        "listCacheServerObjectNames",
+        "viewRemoteClusterStatus",
+        "getTotalHeapSize",
+        "setQueryCollectionsDepth",
+        "getQueryCollectionsDepth",
+        "changeAlertLevel",
+        "backupAllMembers",
+        "revokeMissingDiskStores",
+        "shutDownAllMembers",
+        "queryData",
+        "queryDataForCompressedResult",
+        "setQueryResultSetLimit",       
+    };
+    
+    ResourceOperationCode expectedCodes[] = {
+        ResourceOperationCode.LIST_DS,
+        ResourceOperationCode.LIST_DS,
+        ResourceOperationCode.LIST_DS,
+        ResourceOperationCode.QUERY,
+        ResourceOperationCode.LIST_DS,
+        ResourceOperationCode.CHANGE_ALERT_LEVEL,
+        ResourceOperationCode.BACKUP_MEMBERS,
+        ResourceOperationCode.REVOKE_MISSING_DISKSTORE,
+        ResourceOperationCode.SHUTDOWN,
+        ResourceOperationCode.QUERY,
+        ResourceOperationCode.QUERY,
+        ResourceOperationCode.QUERY
+    };
+        
+    for(int i=0;i<methods.length;i++) {
+      String methodName = methods[i];
+      JMXOperationContext context = new JMXOperationContext(name, methodName);
+      assertEquals(expectedCodes[i],
+          context.getResourceOperationCode());
+      assertEquals(OperationCode.RESOURCE, context.getOperationCode());
+    }
+    
+    JMXConnector cs = getGemfireMBeanServer(port, "tushark", "tushark");;
+    MBeanServerConnection mbeanServer =null;
+    int totalCalls=-1;
+    try {
+      mbeanServer = cs.getMBeanServerConnection();
+      mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(), "listCacheServerObjectNames", null, null);
+      String oldLevel = (String)mbeanServer.getAttribute(MBeanJMXAdapter.getDistributedSystemName(), "AlertLevel");
+      System.out.println("Old Level = " + oldLevel);
+      mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(), "changeAlertLevel", new Object[]{"WARNING"},new String[]{
+        String.class.getCanonicalName()
+      });
+      String newLevel = (String)mbeanServer.getAttribute(MBeanJMXAdapter.getDistributedSystemName(), "AlertLevel");
+      System.out.println("New Level = " + newLevel);
+      
+      
+      //totalCalls = 1 for listCacheServerObjectNames +  changeAlertLevel + 2 for AlertLevel attr
+      totalCalls = 2 + 2 ;
+      totalCalls += checkGetAttributesAndSetAttributes(mbeanServer);
+      assertEquals(totalCalls, (int)TestAccessControl.preCallsTL.get());
+      assertEquals(totalCalls, (int)TestAccessControl.postCallsTL.get());
+      checkAcceeControlMXBean(mbeanServer);
+      
+    } catch (InstanceNotFoundException e1) {
+      e1.printStackTrace();
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (MBeanException e1) {
+      e1.printStackTrace();
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (ReflectionException e1) {
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (IOException e1) {
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (AttributeNotFoundException e) {
+      fail("Error while invoking JMXRMI" + e.getMessage());
+    } catch (MalformedObjectNameException e) {
+      fail("Error while invoking JMXRMI" + e.getMessage());
+    }
+    
+    try {
+      mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(),
+          "backupAllMembers", 
+          new Object[]{"targetPath","baseLinePath"}, 
+          new String[]{String.class.getCanonicalName(), String.class.getCanonicalName()});
+      fail("Should not be authorized for backupAllMembers");
+    } catch (SecurityException e) {
+      //expected
+    } catch(Exception e){
+      e.printStackTrace();
+      fail("Unexpected exception : " + e.getMessage());
     }
-		
-		try {
-			mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(),
-					"backupAllMembers", 
-					new Object[]{"targetPath","baseLinePath"}, 
-					new String[]{String.class.getCanonicalName(), String.class.getCanonicalName()});
-			fail("Should not be authorized for backupAllMembers");
-		} catch (SecurityException e) {
-			//expected
-		} catch(Exception e){
-		  e.printStackTrace();
-			fail("Unexpected exception : " + e.getMessage());
-		}
-		
-		try {
-			mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(),
-					"shutDownAllMembers",null,null);
-			fail("Should not be authorized for shutDownAllMembers");
-		} catch (SecurityException e) {
-			//expected
-		} catch(Exception e){
-			fail("Unexpected exception : " + e.getMessage());
-		}
-		
-		checkCLIContext(mbeanServer);
-		
-		try {
-			cs.close();
-		} catch (IOException e) {
-			fail("Unexpected exception : " + e.getMessage());
-		}
-		
-		
-		
-		
-		cache.close();
-		ds.disconnect();
-	}
-	
+    
+    try {
+      mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(),
+          "shutDownAllMembers",null,null);
+      fail("Should not be authorized for shutDownAllMembers");
+    } catch (SecurityException e) {
+      //expected
+    } catch(Exception e){
+      fail("Unexpected exception : " + e.getMessage());
+    }
+    
+    //2 unsuccessful calls    
+    assertEquals(totalCalls, (int)TestAccessControl.preCallsTL.get());
+    assertEquals(totalCalls, (int)TestAccessControl.postCallsTL.get());
+    
+    checkCLIContext(mbeanServer);totalCalls += 2;       
+    assertEquals(totalCalls, (int)TestAccessControl.preCallsTL.get());
+    assertEquals(totalCalls, (int)TestAccessControl.postCallsTL.get());
+    
+    //Simulate a condition where accessControl return false during postOpAuthZ
+    TestAccessControl.failPostOpIntentionally = true;
+    for(int i=1;i<=3;i++) {
+      try {
+        mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(), "changeAlertLevel", new Object[] { "WARNING" },
+            new String[] { String.class.getCanonicalName() });              
+      } catch (InstanceNotFoundException e) {
+        fail("Unexpected exception : " + e.getMessage());
+      } catch (MBeanException e) {
+        fail("Unexpected exception : " + e.getMessage());
+      } catch (ReflectionException e) {
+        fail("Unexpected exception : " + e.getMessage());
+      } catch (IOException e) {
+        fail("Unexpected exception : " + e.getMessage());
+      }  catch (SecurityException e) {
+        //expected
+        assertEquals(totalCalls+i, (int)TestAccessControl.preCallsTL.get());
+        assertEquals(totalCalls, (int)TestAccessControl.postCallsTL.get());
+      }  
+    }    
+    TestAccessControl.failPostOpIntentionally = false;
+    try {
+      cs.close();
+    } catch (IOException e) {
+      fail("Unexpected exception : " + e.getMessage());
+    }
+    
+    cache.close();
+    ds.disconnect();
+  }
+  
+  private int checkGetAttributesAndSetAttributes(MBeanServerConnection mbeanServer) throws InstanceNotFoundException, ReflectionException, IOException {
+    AttributeList list = mbeanServer.getAttributes(MBeanJMXAdapter.getDistributedSystemName(),
+        new String[]{"TotalHeapSize","TotalRegionEntryCount","TotalRegionCount","TotalMissCount"});    
+    assertNotNull(list);
+    assertEquals(4,list.size());    
+    list = new AttributeList();
+    list.add(new Attribute("QueryResultSetLimit", 1000));    
+    list.add(new Attribute("QueryCollectionsDepth",1000));
+    list = mbeanServer.setAttributes(MBeanJMXAdapter.getDistributedSystemName(),list);
+    assertNotNull(list);
+    assertEquals(2,list.size());
+    return 3;
+  }
+
+  public void testOnlyAuthenticatorNoAuthorization() {    
+    TestAccessControl.resetCallsCounter();    
+    GemFireCacheImpl cache = null;
+    DistributedSystem ds = null;
+    Properties pr = new Properties();
+    pr.put("name", "testJMXOperationContext");
+    pr.put(DistributionConfig.JMX_MANAGER_NAME, "true");
+    pr.put(DistributionConfig.JMX_MANAGER_START_NAME, "true");
+    int port = AvailablePortHelper.getRandomAvailableTCPPort();
+    pr.put(DistributionConfig.JMX_MANAGER_PORT_NAME, String.valueOf(port));
+    pr.put(DistributionConfig.HTTP_SERVICE_PORT_NAME, "0");    
+    pr.put(DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAuthenticator.create");    
+    ds = getSystem(pr);
+    cache = (GemFireCacheImpl) CacheFactory.create(ds);
+    JMXConnector cs = getGemfireMBeanServer(port, "tushark", "tushark");;
+    MBeanServerConnection mbeanServer =null;
+    try {
+      mbeanServer = cs.getMBeanServerConnection();
+      mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(), "listCacheServerObjectNames", null, null);
+      String oldLevel = (String)mbeanServer.getAttribute(MBeanJMXAdapter.getDistributedSystemName(), "AlertLevel");
+      System.out.println("Old Level = " + oldLevel);
+      mbeanServer.invoke(MBeanJMXAdapter.getDistributedSystemName(), "changeAlertLevel", new Object[]{"WARNING"},new String[]{
+        String.class.getCanonicalName()
+      });
+      String newLevel = (String)mbeanServer.getAttribute(MBeanJMXAdapter.getDistributedSystemName(), "AlertLevel");
+      System.out.println("New Level = " + newLevel);      
+      //totalCalls = 0 since not AccessControl is invoked     
+      assertEquals(0, (int)TestAccessControl.preCallsTL.get());
+      assertEquals(0, (int)TestAccessControl.postCallsTL.get());      
+    } catch (InstanceNotFoundException e1) {
+      e1.printStackTrace();
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (MBeanException e1) {
+      e1.printStackTrace();
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (ReflectionException e1) {
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (IOException e1) {
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (AttributeNotFoundException e) {
+      fail("Error while invoking JMXRMI" + e.getMessage());
+    } 
+    cache.close();
+    ds.disconnect();
+  }
+  
+  public void testAuthenticationUsingPropertiesBag(){
+    TestAccessControl.resetCallsCounter();    
+    GemFireCacheImpl cache = null;
+    DistributedSystem ds = null;
+    Properties pr = new Properties();
+    pr.put("name", "testJMXOperationContext");
+    pr.put(DistributionConfig.JMX_MANAGER_NAME, "true");
+    pr.put(DistributionConfig.JMX_MANAGER_START_NAME, "true");
+    int port = AvailablePortHelper.getRandomAvailableTCPPort();
+    pr.put(DistributionConfig.JMX_MANAGER_PORT_NAME, String.valueOf(port));
+    pr.put(DistributionConfig.HTTP_SERVICE_PORT_NAME, "0");    
+    pr.put(DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAuthenticator.create");
+    pr.put(DistributionConfig.SECURITY_CLIENT_ACCESSOR_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl.create");
+    pr.put(DistributionConfig.SECURITY_CLIENT_ACCESSOR_PP_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl.create");
+    ds = getSystem(pr);
+    cache = (GemFireCacheImpl) CacheFactory.create(ds);
+    
+    Properties userProperties = new Properties();
+    userProperties.put("GoTSecret", "JohnSnowIsIceAndFire");
+    JMXConnector cs = getGemfireMBeanServer(port, userProperties);
+    MBeanServerConnection mbeanServer =null;
+    try {
+      mbeanServer = cs.getMBeanServerConnection();      
+      String oldLevel = (String)mbeanServer.getAttribute(MBeanJMXAdapter.getDistributedSystemName(), "AlertLevel");
+      System.out.println("Old Level = " + oldLevel);      
+      cs.close();
+    } catch (InstanceNotFoundException e1) {
+      e1.printStackTrace();
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (MBeanException e1) {
+      e1.printStackTrace();
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (ReflectionException e1) {
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (IOException e1) {
+      fail("Error while invoking JMXRMI " + e1.getMessage());
+    } catch (AttributeNotFoundException e) {
+      fail("Error while invoking JMXRMI" + e.getMessage());
+    }
+    
+    try {
+      userProperties = new Properties();
+      userProperties.put("GoTSecret", "JoffreyIsRightfulKing");
+      cs = getGemfireMBeanServer(port, userProperties);
+      fail("Authentication should fail");
+    } catch (AuthenticationFailedException e) {
+      //expected
+    } catch (SecurityException e) {
+      //expected
+    } catch(Exception e){
+      e.printStackTrace();
+      fail("Unexpected error " + e.getMessage());      
+    }
+    cache.close();
+    ds.disconnect();
+  }
+  
+  private void checkAcceeControlMXBean(MBeanServerConnection mbeanServer) throws MalformedObjectNameException,
+      InstanceNotFoundException, MBeanException, ReflectionException, IOException {
+    // Checking accessControlMXBean
+    System.out.println("Checking access via AccessControlMbean");
+    ResourceOperationCode authorizedOps[] = { ResourceOperationCode.LIST_DS, ResourceOperationCode.LIST_DS,
+        ResourceOperationCode.CHANGE_ALERT_LEVEL, ResourceOperationCode.LOCATE_ENTRY };
+    ObjectName accControlON = new ObjectName(ResourceConstants.OBJECT_NAME_ACCESSCONTROL);
+    for (ResourceOperationCode c : authorizedOps) {
+      boolean result = (Boolean) mbeanServer.invoke(accControlON, "authorize",
+          new Object[] { c.toString() },
+          new String[] { String.class.getCanonicalName() });
+      assertTrue(result);
+    }
+    
+    //check accessControlMBean is hidden from generic listing
+    Set<ObjectInstance> instanceSet = mbeanServer.queryMBeans(null, null);
+    for(ObjectInstance oi : instanceSet) {
+      if(oi.getObjectName().equals(accControlON))
+        fail("Found AccessControl Mbean in queryMbeans");
+    }
+    
+    Set<ObjectName> onSet = mbeanServer.queryNames(null, null);
+    for(ObjectName on : onSet) {
+      if(on.equals(accControlON))
+        fail("Found AccessControl Mbean in queryNames");
+    }
+
+  }
+
   private void checkCLIContext(MBeanServerConnection mbeanServer) {
     DistributedSystemMXBean proxy = JMX.newMXBeanProxy(mbeanServer, MBeanJMXAdapter.getDistributedSystemName(),
         DistributedSystemMXBean.class);
@@ -298,81 +525,198 @@ public class ResourceOperationJUnit  extends TestCase {
       System.out.println("Result = " + result);
     } catch (Exception e) {
       System.out.println("Excpetion e " + e.getMessage());
-      e.printStackTrace();
+      fail(e.getMessage());
+    }
+  }
+  
+  public void testAllCommandsAreAnnotated() {
+    GemFireCacheImpl cache = null;
+    DistributedSystem ds = null;
+    Properties pr = new Properties();
+    pr.put("name", "testJMXOperationContext");
+    pr.put(DistributionConfig.JMX_MANAGER_NAME, "true");
+    pr.put(DistributionConfig.JMX_MANAGER_START_NAME, "true");
+    int port = AvailablePortHelper.getRandomAvailableTCPPort();
+    pr.put(DistributionConfig.JMX_MANAGER_PORT_NAME, String.valueOf(port));
+    pr.put(DistributionConfig.HTTP_SERVICE_PORT_NAME, "0");
+    pr.put(DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAuthenticator.create");
+    pr.put(DistributionConfig.SECURITY_CLIENT_ACCESSOR_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl.create");
+    pr.put(DistributionConfig.SECURITY_CLIENT_ACCESSOR_PP_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl.create");
+    ds = getSystem(pr);
+    cache = (GemFireCacheImpl) CacheFactory.create(ds);
+    
+    CommandManager manager = CommandManager.getExisting();
+    List<String> notFoundList = new ArrayList<String>();
+    Map<String,CommandTarget> map = manager.getCommands();
+    for(Map.Entry<String,CommandTarget> entry : map.entrySet()) {
+      String commandName = entry.getKey();
+      CommandTarget target = entry.getValue();
+      GfshMethodTarget methodTarget = target.getGfshMethodTarget();
+      boolean found=false;
+      Annotation ans[] = methodTarget.getMethod().getDeclaredAnnotations();
+      for(Annotation an : ans){
+        if(an instanceof ResourceOperation) {
+          String opcode= ((ResourceOperation) an).operation();
+          LogService.getLogger().info("For command " + commandName + " OpCode="+ opcode);
+          found = true;
+        }
+      }
+      if(!found)
+        notFoundList.add(commandName);
+    }
+    System.out.println("Command without any annotation " + notFoundList);
+    assertEquals(0,notFoundList.size());
+    cache.close();
+    ds.disconnect();
+  }
+
+  public void testCLIOperationContext() { 
+    GemFireCacheImpl cache = null;
+    DistributedSystem ds = null;
+    Properties pr = new Properties();
+    pr.put("name", "testJMXOperationContext");
+    pr.put(DistributionConfig.JMX_MANAGER_NAME, "true");
+    pr.put(DistributionConfig.JMX_MANAGER_START_NAME, "true");
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    pr.put(DistributionConfig.JMX_MANAGER_PORT_NAME, String.valueOf(port));
+    pr.put(DistributionConfig.HTTP_SERVICE_PORT_NAME, "0");
+    pr.put(DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAuthenticator.create");
+    pr.put(DistributionConfig.SECURITY_CLIENT_ACCESSOR_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl.create");
+    pr.put(DistributionConfig.SECURITY_CLIENT_ACCESSOR_PP_NAME, "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl.create");
+    ds = getSystem(pr);
+    cache = (GemFireCacheImpl) CacheFactory.create(ds);
+    
+    String[] commands = {       
+        "export data --region=value --file=value --member=value",
+        "import data --region=value --file=value --member=value",
+        "rebalance",
+        "get --key=k1 --region=/region1",
+        "put --key=k1 --value=v1 --region=/region1",
+        "locate entry --key=k1 --region=/region1",
+        "query --query=\"select * from /region1\"",       
+        "remove --key=k1 --region=/region1",                
+        "remove --region=/region1 --all=true", //region clear
+        "create region --name=r1 --type=REPLICATE",
+        "destroy region --name=/r1", 
+        "execute function --id=func1",
+        "close durable-cq --durable-client-id=value --durable-cq-name=value"
+         //"stop cq"
+        //"removeall",
+        //"get durable cqs",        
+    };
+    
+    ResourceOperationCode expectedResourceCodes[] = {       
+        ResourceOperationCode.EXPORT_DATA,
+        ResourceOperationCode.IMPORT_DATA,
+        ResourceOperationCode.REBALANCE,
+        ResourceOperationCode.GET,
+        ResourceOperationCode.PUT,
+        ResourceOperationCode.LOCATE_ENTRY,
+        ResourceOperationCode.QUERY,
+        ResourceOperationCode.REMOVE,
+        ResourceOperationCode.REMOVE,
+        ResourceOperationCode.CREATE_REGION,
+        ResourceOperationCode.DESTROY_REGION,
+        ResourceOperationCode.EXECUTE_FUNCTION,
+        ResourceOperationCode.CLOSE_DURABLE_CQ,
+    };
+    
+    OperationCode expectedOpCodes[] = {        
+        OperationCode.RESOURCE,
+        OperationCode.RESOURCE,
+        OperationCode.RESOURCE,
+        OperationCode.GET,
+        OperationCode.PUT,
+        OperationCode.GET,
+        OperationCode.QUERY,
+        OperationCode.DESTROY,
+        OperationCode.REMOVEALL,
+        OperationCode.REGION_CREATE,
+        OperationCode.REGION_DESTROY,
+        OperationCode.EXECUTE_FUNCTION,
+        OperationCode.CLOSE_CQ,
+    };
+    
+    for(int i=0;i<commands.length;i++){
+      CLIOperationContext ctx = new CLIOperationContext(commands[i]);
+      System.out.println("Context " + ctx);
+      assertEquals(expectedResourceCodes[i],ctx.getResourceOperationCode());
+      assertEquals(expectedOpCodes[i],ctx.getOperationCode());
+    }
+    
+    cache.close();
+    ds.disconnect();
+  }
+  
+  public void testResourceOpCodeAllowedOp() {
+    assertTrue(ResourceOperationCode.ADMIN.allowedOp(ResourceOperationCode.LIST_DS));
+    assertTrue(ResourceOperationCode.DATA_READ.allowedOp(ResourceOperationCode.LIST_DS));
+    assertTrue(ResourceOperationCode.DATA_WRITE.allowedOp(ResourceOperationCode.LIST_DS));
+    assertTrue(ResourceOperationCode.MONITOR.allowedOp(ResourceOperationCode.LIST_DS));
+
+    assertTrue(ResourceOperationCode.MONITOR.allowedOp(ResourceOperationCode.DATA_READ));
+    assertTrue(ResourceOperationCode.DATA_WRITE.allowedOp(ResourceOperationCode.DATA_READ));
+    assertTrue(ResourceOperationCode.ADMIN.allowedOp(ResourceOperationCode.DATA_READ));
+
+    assertTrue(ResourceOperationCode.MONITOR.allowedOp(ResourceOperationCode.PULSE_DASHBOARD));
+    assertTrue(ResourceOperationCode.DATA_WRITE.allowedOp(ResourceOperationCode.PULSE_DASHBOARD));
+    assertTrue(ResourceOperationCode.ADMIN.allowedOp(ResourceOperationCode.PULSE_DASHBOARD));
+
+    assertFalse(ResourceOperationCode.PULSE_DASHBOARD.allowedOp(ResourceOperationCode.BECOME_LOCK_GRANTOR));
+    assertTrue(ResourceOperationCode.PULSE_DASHBOARD.allowedOp(ResourceOperationCode.PULSE_DASHBOARD));
+
+    assertTrue(ResourceOperationCode.ADMIN.allowedOp(ResourceOperationCode.SHUTDOWN));
+    assertFalse(ResourceOperationCode.DATA_READ.allowedOp(ResourceOperationCode.SHUTDOWN));
+    assertFalse(ResourceOperationCode.DATA_WRITE.allowedOp(ResourceOperationCode.SHUTDOWN));
+    assertFalse(ResourceOperationCode.MONITOR.allowedOp(ResourceOperationCode.SHUTDOWN));
+
+    assertTrue(ResourceOperationCode.ADMIN.allowedOp(ResourceOperationCode.BECOME_LOCK_GRANTOR));
+    assertFalse(ResourceOperationCode.DATA_READ.allowedOp(ResourceOperationCode.BECOME_LOCK_GRANTOR));
+    assertTrue(ResourceOperationCode.DATA_WRITE.allowedOp(ResourceOperationCode.BECOME_LOCK_GRANTOR));
+    assertFalse(ResourceOperationCode.MONITOR.allowedOp(ResourceOperationCode.BECOME_LOCK_GRANTOR));
+
+    assertTrue(ResourceOperationCode.ADMIN.allowedOp(ResourceOperationCode.EXPORT_STACKTRACE));
+    assertFalse(ResourceOperationCode.DATA_READ.allowedOp(ResourceOperationCode.EXPORT_STACKTRACE));
+    assertFalse(ResourceOperationCode.DATA_WRITE.allowedOp(ResourceOperationCode.EXPORT_STACKTRACE));
+    assertTrue(ResourceOperationCode.MONITOR.allowedOp(ResourceOperationCode.EXPORT_STACKTRACE));
+  }
+  
+  private JMXConnector getGemfireMBeanServer(int port, Properties pr) {
+    return _getGemfireMBeanServer(port, pr);
+  }
+  
+  private JMXConnector getGemfireMBeanServer(int port, String user, String pwd) {
+    String[] creds = null;
+    if(user!=null) 
+      creds = new String[]{ user, pwd };
+    return _getGemfireMBeanServer(port, creds);
+  }
+  
+  @SuppressWarnings({ "unchecked", "rawtypes" })
+  private JMXConnector _getGemfireMBeanServer(int port, Object creds) {
+    JMXServiceURL url;
+    try {
+      url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + port + "/jmxrmi");
+      if (creds != null) {
+        Map env = new HashMap();        
+        env.put(JMXConnector.CREDENTIALS, creds);
+        JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
+        return jmxc;
+      } else {
+        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
+        return jmxc;
+      }
+    } catch (MalformedURLException e) {
+      fail("Error connecting to port=" + port + " " + e.getMessage());
+    } catch (IOException e) {
+      fail("Error connecting to port=" + port + " " + e.getMessage());
     }
+    return null;
   }
 
-	public void testCLIOperationContext() {	
-		System.setProperty("resource-auth-accessor", "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAccessControl");
-		System.setProperty("resource-authenticator", "com.gemstone.gemfire.management.internal.security.ResourceOperationJUnit$TestAuthenticator");
-		GemFireCacheImpl cache = null;
-		DistributedSystem ds = null;
-		Properties pr = new Properties();
-		pr.put("name", "testJMXOperationContext");
-		pr.put(DistributionConfig.JMX_MANAGER_NAME, "true");
-		pr.put(DistributionConfig.JMX_MANAGER_START_NAME, "true");
-		int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-		pr.put(DistributionConfig.JMX_MANAGER_PORT_NAME, String.valueOf(port));
-		pr.put(DistributionConfig.HTTP_SERVICE_PORT_NAME, "0");
-		ds = getSystem(pr);
-		cache = (GemFireCacheImpl) CacheFactory.create(ds);
-		
-		String[] commands = {
-				"put --key=k1 --value=v1 --region=/region1",
-				"locate entry --key=k1 --region=/region1",
-				"query --query=\"select * from /region1\"",
-				"export data --region=value --file=value --member=value",
-				"import data --region=value --file=value --member=value",
-				"rebalance"
-		};
-		
-		ResourceOperationCode expectedCodes[] = {
-				ResourceOperationCode.PUT_REGION,
-				ResourceOperationCode.LOCATE_ENTRY_REGION,
-				ResourceOperationCode.QUERYDATA_DS,
-				ResourceOperationCode.EXPORT_DATA_REGION,
-				ResourceOperationCode.IMPORT_DATA_REGION,
-				ResourceOperationCode.REBALANCE_DS
-		};
-		
-		for(int i=0;i<commands.length;i++){
-			CLIOperationContext ctx = new CLIOperationContext(commands[i]);
-			System.out.println("Context " + ctx);
-			assertEquals(expectedCodes[i],ctx.getResourceOperationCode());
-		}
-		
-		cache.close();
-		ds.disconnect();
-	}
-	
-	
-	
-	private JMXConnector getGemfireMBeanServer(int port, String user, String pwd) {
-		JMXServiceURL url;
-		try {
-			url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:"+ port +"/jmxrmi");
-			if(user!=null){
-				Map env = new HashMap();
-			    String[] creds = {user, pwd};
-			    env.put(JMXConnector.CREDENTIALS, creds);
-			    JMXConnector jmxc =  JMXConnectorFactory.connect(url,env);
-			    return jmxc;
-			} else {
-				JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
-				return jmxc;
-			}
-		} catch (MalformedURLException e) {
-			fail("Error connecting to port=" + port  + " " + e.getMessage());
-		} catch (IOException e) {
-			fail("Error connecting to port=" + port  + " " + e.getMessage());
-		}
-		return null;
-	}
-
-
-
-	private static DistributedSystem getSystem(Properties properties) {
-	    return DistributedSystem.connect(properties);
-	  }
+  private static DistributedSystem getSystem(Properties properties) {
+      return DistributedSystem.connect(properties);
+    }
 
 }
+

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestTestUtils.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestTestUtils.java b/gemfire-core/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestTestUtils.java
index d2499fe..78210bd 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestTestUtils.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/rest/internal/web/controllers/RestTestUtils.java
@@ -11,12 +11,14 @@ import java.net.URI;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.List;
+
 import org.springframework.http.converter.ByteArrayHttpMessageConverter;
 import org.springframework.http.converter.HttpMessageConverter;
 import org.springframework.http.converter.ResourceHttpMessageConverter;
 import org.springframework.http.converter.StringHttpMessageConverter;
 import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean;
 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
+import org.springframework.util.StringUtils;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.util.UriComponentsBuilder;
 
@@ -98,4 +100,12 @@ public class RestTestUtils  {
     return UriComponentsBuilder.fromUri(baseUrl).pathSegment(pathSegments)
         .build().toUri();
   }
+  
+  public static String createRestURL(String baseURL, Object requestPart) {
+    if(StringUtils.isEmpty(requestPart)) {
+      return baseURL + RestTestUtils.GEMFIRE_REST_API_CONTEXT + RestTestUtils.GEMFIRE_REST_API_VERSION;
+    }else {
+      return baseURL + RestTestUtils.GEMFIRE_REST_API_CONTEXT + RestTestUtils.GEMFIRE_REST_API_VERSION + requestPart;
+    }
+  }
 }

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/AbstractBaseController.java
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/AbstractBaseController.java b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/AbstractBaseController.java
index feed8c7..2a44403 100644
--- a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/AbstractBaseController.java
+++ b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/AbstractBaseController.java
@@ -68,6 +68,7 @@ import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
 import com.gemstone.gemfire.rest.internal.web.exception.MalformedJsonException;
 import com.gemstone.gemfire.rest.internal.web.exception.RegionNotFoundException;
 import com.gemstone.gemfire.rest.internal.web.exception.ResourceNotFoundException;
+import com.gemstone.gemfire.rest.internal.web.security.RestRequestFilter;
 import com.gemstone.gemfire.rest.internal.web.util.ArrayUtils;
 import com.gemstone.gemfire.rest.internal.web.util.IdentifiableUtils;
 import com.gemstone.gemfire.rest.internal.web.util.JSONUtils;
@@ -96,6 +97,7 @@ public abstract class AbstractBaseController {
   protected static final String UTF_8 = "UTF-8";
   protected static final String DEFAULT_ENCODING = UTF_8;
   private static final AtomicLong ID_SEQUENCE = new AtomicLong(0l);
+  protected static final String AUTH_TOKEN_HEADER = "security-gfrest-authtoken";
   
   //private Cache cache = GemFireCacheImpl.getExisting(null);
   
@@ -184,13 +186,13 @@ public abstract class AbstractBaseController {
     }              
   }
   
-  public ResponseEntity<String> processQueryResponse (Object  queryResult, String queryId) throws JSONException {
+  public ResponseEntity<String> processQueryResponse (Object  queryResult, String queryId, HttpHeaders headers) throws JSONException {
     if(queryResult instanceof Collection<?>){
       Collection<Object> result = (Collection<Object>) queryResult;
       String queryResultAsJson =  JSONUtils.convertCollectionToJson(result);
       
-      final HttpHeaders headers = new HttpHeaders();
-      headers.setLocation(toUri("queries", queryId));    
+      headers.setLocation(toUri("queries", queryId)); 
+ 
       return new ResponseEntity<String>(queryResultAsJson, headers, HttpStatus.OK);
     }else {
       throw new GemfireRestException("Server has encountered error while generating query result into restful format(JSON)!");
@@ -680,7 +682,7 @@ public abstract class AbstractBaseController {
     } 
   }
   
-  public ResponseEntity<String> updateSingleKey(final String region, final String key, final String json, final String opValue){    
+  public ResponseEntity<String> updateSingleKey(final String region, final String key, final String json, final String opValue, HttpHeaders headers){    
     
     final JSONTypes jsonType = validateJsonAndFindType(json);
     
@@ -707,13 +709,12 @@ public abstract class AbstractBaseController {
         }
     }
         
-    final HttpHeaders headers = new HttpHeaders();
     headers.setLocation(toUri(region, key));
     return new ResponseEntity<String>(existingValue, headers, (existingValue == null ? HttpStatus.OK : HttpStatus.CONFLICT));        
   }
   
   
-  public ResponseEntity<String> updateMultipleKeys(final String region, final String[] keys, final String json){
+  public ResponseEntity<String> updateMultipleKeys(final String region, final String[] keys, final String json, HttpHeaders headers){
     
     JSONArray jsonArr = null;
     try {
@@ -743,8 +744,7 @@ public abstract class AbstractBaseController {
     if(!CollectionUtils.isEmpty(map)){ 
       putPdxValues(region, map);
     }
-    
-    HttpHeaders headers = new HttpHeaders();
+   
     headers.setLocation(toUri(region, StringUtils.arrayToCommaDelimitedString(keys)));
     return new ResponseEntity<String>(headers, HttpStatus.OK);
   }
@@ -829,4 +829,22 @@ public abstract class AbstractBaseController {
     targetedMembers.add(c.getDistributedSystem().getDistributedMember());
     return targetedMembers;
   }
+  
+  protected void setAuthTokenHeader(HttpHeaders headers) {
+    Map<String, Object> envMap = (Map<String, Object>)RestRequestFilter.getEnvironment();
+    boolean isSecurityEnabled = (boolean) envMap.get("isSecurityEnabled");
+  
+    if(isSecurityEnabled == false)
+      return;
+  
+    headers.set(AUTH_TOKEN_HEADER,(String)envMap.get("authToken"));
+    
+  }
+  
+  protected String getAuthToken(){
+    Map<String, Object> envMap = (Map<String, Object>)RestRequestFilter.getEnvironment();
+    return (String)envMap.get("authToken");
+  }
+  
 }
+

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/BaseControllerAdvice.java
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/BaseControllerAdvice.java b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/BaseControllerAdvice.java
index 5ae88bc..d862448 100644
--- a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/BaseControllerAdvice.java
+++ b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/BaseControllerAdvice.java
@@ -25,6 +25,9 @@ import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
 import com.gemstone.gemfire.rest.internal.web.exception.MalformedJsonException;
 import com.gemstone.gemfire.rest.internal.web.exception.RegionNotFoundException;
 import com.gemstone.gemfire.rest.internal.web.exception.ResourceNotFoundException;
+import com.gemstone.gemfire.security.AuthenticationFailedException;
+import com.gemstone.gemfire.security.AuthenticationRequiredException;
+import com.gemstone.gemfire.security.NotAuthorizedException;
 
 /**
  * The CrudControllerAdvice class handles exception thrown while serving the REST request
@@ -33,7 +36,7 @@ import com.gemstone.gemfire.rest.internal.web.exception.ResourceNotFoundExceptio
  * @since 8.0
  */
 
-@ControllerAdvice
+//@ControllerAdvice
 @SuppressWarnings("unused")
 public class BaseControllerAdvice extends AbstractBaseController{
 
@@ -134,5 +137,42 @@ public class BaseControllerAdvice extends AbstractBaseController{
     return convertErrorAsJson(cause.getMessage());
   }
   
+  /**
+   * Handles NotAuthorizedException, occurring when REST service encounters unAuthorized access.
+   * <p/>
+   * @param e the RuntimeException thrown when request is not authorized to perform the operation.
+   * @return the String message from the RuntimeException.
+   */
+  @ExceptionHandler({ NotAuthorizedException.class })
+  @ResponseBody
+  @ResponseStatus(HttpStatus.UNAUTHORIZED)
+  public String handleException(final NotAuthorizedException e) {
+    return convertErrorAsJson(e.getMessage());
+  }
+  
+  /**
+   * Handles AuthenticationFailedException, occurring when REST service can not authenticate the request.
+   * <p/>
+   * @param e the RuntimeException thrown when request is not authenticated to perform the operation.
+   * @return the String message from the RuntimeException.
+   */
+  @ExceptionHandler({ AuthenticationFailedException.class })
+  @ResponseBody
+  @ResponseStatus(HttpStatus.FORBIDDEN)
+  public String handleException(final AuthenticationFailedException e) {
+    return convertErrorAsJson(e.getMessage());
+  }
+  
+  /**
+   * Handles AuthenticationRequiredException, occurring when REST service can not find the security credentials i nthe request.
+   * <p/>
+   * @param e the RuntimeException thrown when request does not contains security credentials for authentication.
+   * @return the String message from the RuntimeException.
+   */
+  @ExceptionHandler({ AuthenticationRequiredException.class })
+  @ResponseBody
+  @ResponseStatus(HttpStatus.FORBIDDEN)
+  public String handleException(final AuthenticationRequiredException e) {
+    return convertErrorAsJson(e.getMessage());
+  }
 }
-

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/CommonCrudController.java
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/CommonCrudController.java b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/CommonCrudController.java
index ef52347..fb7d16d 100644
--- a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/CommonCrudController.java
+++ b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/CommonCrudController.java
@@ -27,12 +27,17 @@ import com.gemstone.gemfire.cache.execute.Execution;
 import com.gemstone.gemfire.cache.execute.FunctionException;
 import com.gemstone.gemfire.cache.execute.FunctionService;
 import com.gemstone.gemfire.cache.execute.ResultCollector;
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
 import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
 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.RestServersResultCollector;
 import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
+import com.gemstone.gemfire.rest.internal.web.security.AuthorizationProvider;
+import com.gemstone.gemfire.rest.internal.web.security.RestRequestFilter;
 import com.gemstone.gemfire.rest.internal.web.util.JSONUtils;
+import com.gemstone.gemfire.security.NotAuthorizedException;
 import org.json.JSONException;
 import com.wordnik.swagger.annotations.ApiOperation;
 import com.wordnik.swagger.annotations.ApiResponse;
@@ -71,10 +76,23 @@ public abstract class CommonCrudController extends AbstractBaseController {
       logger.debug("Listing all resources (Regions) in GemFire...");
     }
     
-    final Set<Region<?, ?>> regions = getCache().rootRegions();
-    String listRegionsAsJson =  JSONUtils.formulateJsonForListRegions(regions, "regions");
     final HttpHeaders headers = new HttpHeaders();  
     headers.setLocation(toUri());
+    
+    //Do request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        AuthorizationProvider.listRegionsAuthorize(OperationCode.LIST, true, "LIST_REGIONS");
+      }catch(NotAuthorizedException nae){
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+   
+    final Set<Region<?, ?>> regions = getCache().rootRegions();
+    String listRegionsAsJson =  JSONUtils.formulateJsonForListRegions(regions, "regions");
+    
     return new ResponseEntity<String>(listRegionsAsJson, headers, HttpStatus.OK);
   }
   
@@ -98,16 +116,35 @@ public abstract class CommonCrudController extends AbstractBaseController {
   public ResponseEntity<?> keys(@PathVariable("region") String region){ 
     
     if(logger.isDebugEnabled()){
-      logger.debug("Reading all Keys in Region ({})...", region);
+      logger.debug("Listing all Keys in Region ({})...", region);
     }
     
     region = decode(region);
-    
-    Object[] keys = getKeys(region, null);  
-    
-    String listKeysAsJson =  JSONUtils.formulateJsonForListKeys(keys, "keys");
     final HttpHeaders headers = new HttpHeaders();  
     headers.setLocation(toUri(region, "keys"));
+    
+    //Request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        AuthorizationProvider.keySetAuthorize(region);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
+    Set<Object> keys = getRegion(region).keySet();
+    
+    //Post authorization
+    if(AuthorizationProvider.isSecurityEnabled()){
+      try{
+        AuthorizationProvider.keySetAuthorizePP(region, keys);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    String listKeysAsJson =  JSONUtils.formulateJsonForListKeys(keys.toArray(), "keys");
     return new ResponseEntity<String>(listKeysAsJson, headers, HttpStatus.OK);
   }
   
@@ -136,9 +173,21 @@ public abstract class CommonCrudController extends AbstractBaseController {
     }
     
     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.deleteAuthorize(region, keys, null);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
     
     deleteValues(region, (Object[])keys);
-    return new ResponseEntity<Object>(HttpStatus.OK);
+    return new ResponseEntity<Object>(headers, HttpStatus.OK);
   }
 
   /**
@@ -164,9 +213,21 @@ public abstract class CommonCrudController extends AbstractBaseController {
     }
     
     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.deleteAllAuthorize(region, null);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
     
     deleteValues(region);
-    return new ResponseEntity<Object>(HttpStatus.OK);
+    return new ResponseEntity<Object>(headers, HttpStatus.OK);
   }
   
   @RequestMapping(method = { RequestMethod.GET, RequestMethod.HEAD }, value = "/ping")
@@ -180,6 +241,7 @@ public abstract class CommonCrudController extends AbstractBaseController {
     @ApiResponse( code = 500, message = "if GemFire throws an error or exception" )   
   } )
   public ResponseEntity<?> ping() {
+    // Request Authorization not required.
     return new ResponseEntity<Object>(HttpStatus.OK);
   }
   
@@ -194,12 +256,13 @@ public abstract class CommonCrudController extends AbstractBaseController {
     @ApiResponse( code = 500, message = "if GemFire throws an error or exception" )   
   } )
   public ResponseEntity<?> servers() {
+    //Request Authorization not required.
     Execution function = null;
       
     if(logger.isDebugEnabled()){
       logger.debug("Executing function to get REST enabled gemfire nodes in the DS!");
     }
-      
+    
     try {
       function = FunctionService.onMembers(getAllMembersInDS());
     } catch(FunctionException fe) {

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/FunctionAccessController.java
----------------------------------------------------------------------
diff --git a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/FunctionAccessController.java b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/FunctionAccessController.java
index 45d6f66..09acbcd 100644
--- a/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/FunctionAccessController.java
+++ b/gemfire-web-api/src/main/java/com/gemstone/gemfire/rest/internal/web/controllers/FunctionAccessController.java
@@ -33,10 +33,16 @@ import com.gemstone.gemfire.cache.execute.Function;
 import com.gemstone.gemfire.cache.execute.FunctionException;
 import com.gemstone.gemfire.cache.execute.FunctionService;
 import com.gemstone.gemfire.cache.execute.ResultCollector;
+import com.gemstone.gemfire.cache.operations.ExecuteFunctionOperationContext;
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
 import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.management.internal.RestAgent;
 import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
+import com.gemstone.gemfire.rest.internal.web.security.AuthorizationProvider;
+import com.gemstone.gemfire.rest.internal.web.security.FunctionExecutionPostAuthzRC;
 import com.gemstone.gemfire.rest.internal.web.util.ArrayUtils;
 import com.gemstone.gemfire.rest.internal.web.util.JSONUtils;
+import com.gemstone.gemfire.security.NotAuthorizedException;
 import org.json.JSONException;
 import com.wordnik.swagger.annotations.Api;
 import com.wordnik.swagger.annotations.ApiOperation;
@@ -93,10 +99,22 @@ public class FunctionAccessController extends AbstractBaseController {
       logger.debug("Listing all registered Functions in GemFire...");
     }
     
-    final Map<String, Function> registeredFunctions = FunctionService.getRegisteredFunctions();
-    String listFunctionsAsJson =  JSONUtils.formulateJsonForListFunctionsCall(registeredFunctions.keySet());
     final HttpHeaders headers = new HttpHeaders();  
     headers.setLocation(toUri("functions"));
+    
+    //Do request(Pre) authorization if security is enabled.
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);  
+      AuthorizationProvider.init();
+      try{
+        AuthorizationProvider.listFunctionsAuthorize(OperationCode.LIST, true, "LIST_FUNCTIONS");
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
+    final Map<String, Function> registeredFunctions = FunctionService.getRegisteredFunctions();
+    String listFunctionsAsJson =  JSONUtils.formulateJsonForListFunctionsCall(registeredFunctions.keySet());
     return new ResponseEntity<String>(listFunctionsAsJson, headers, HttpStatus.OK);
   } 
   
@@ -133,6 +151,27 @@ public class FunctionAccessController extends AbstractBaseController {
     Execution function = null;
     functionId = decode(functionId);
     
+    boolean isOptimizedForWrite = FunctionService.getFunction(functionId).optimizeForWrite();
+    Object[] args = null;
+    final HttpHeaders headers = new HttpHeaders();
+    
+    if(argsInBody != null) 
+    {
+      args = jsonToObjectArray(argsInBody);
+    }
+    
+    //Request(Pre) authorization if security is enabled.
+    ExecuteFunctionOperationContext fContext = null;
+    if(AuthorizationProvider.isSecurityEnabled()){
+      setAuthTokenHeader(headers);
+      AuthorizationProvider.init();
+      try{
+        fContext = AuthorizationProvider.executeFunctionAuthorize(functionId, region, null, args, isOptimizedForWrite);
+      }catch(NotAuthorizedException nae) {
+        return new ResponseEntity<String>(headers, HttpStatus.UNAUTHORIZED);
+      }
+    }
+    
     if (StringUtils.hasText(region)) {
       if(logger.isDebugEnabled()){
         logger.debug("Executing Function ({}) with arguments ({}) on Region ({})...", functionId,
@@ -181,23 +220,32 @@ public class FunctionAccessController extends AbstractBaseController {
         throw new GemfireRestException("Disributed system does not contain any valid data node to run the specified  function!", fe);
       }
     }
-
+    
     final ResultCollector<?, ?> results;
     
     try {
-      if(argsInBody != null) 
-      {
-        Object[] args = jsonToObjectArray(argsInBody);
-        
-        //execute function with specified arguments
-        if(args.length == 1){
+      //Post Authorization if security is enabled.
+      if(AuthorizationProvider.isSecurityEnabled() && RestAgent.getAuthorizeRequestPP(getAuthToken()) != null) {
+        if (fContext == null){
+          fContext = new ExecuteFunctionOperationContext(functionId, region, null, args, isOptimizedForWrite, true);
+        }
+        if(args != null && args.length == 1){        
+          results = function.withArgs(args[0]).withCollector(new FunctionExecutionPostAuthzRC(fContext)).execute(functionId);
+        }else if (args != null && args.length > 1) {
+          results = function.withArgs(args).withCollector(new FunctionExecutionPostAuthzRC(fContext)).execute(functionId);
+        }else {
+          //execute function with no args
+          results = function.withCollector(new FunctionExecutionPostAuthzRC(fContext)).execute(functionId);
+        }
+      }else {
+        if(args != null && args.length == 1){        
           results = function.withArgs(args[0]).execute(functionId);
-        } else {
+        }else if (args != null && args.length > 1) {
           results = function.withArgs(args).execute(functionId);
+        }else {
+          //execute function with no args
+          results = function.execute(functionId);
         }
-      }else { 
-        //execute function with no args
-        results = function.execute(functionId);
       }
     } catch(ClassCastException cce){
       throw new GemfireRestException("Key is of an inappropriate type for this region!", cce);
@@ -215,7 +263,6 @@ public class FunctionAccessController extends AbstractBaseController {
       Object functionResult = results.getResult();
     
       if(functionResult instanceof List<?>) {
-        final HttpHeaders headers = new HttpHeaders();
         headers.setLocation(toUri("functions", functionId));
       
         try {


[6/6] incubator-geode git commit: GEODE-77 : Integrated Security Code Merge Review board url : https://reviews.apache.org/r/37209/

Posted by tu...@apache.org.
GEODE-77 : Integrated Security Code Merge
Review board url : https://reviews.apache.org/r/37209/

This is manual merge of code from int_security branch.

Testing done : JMX RMI-connector testing done from JConsole, Gfsh interactive testing with different roles. DUnits are not yet integrated into open.

Adding description about changes done

JMX - Key Changes

	ManagementAgent.java
		Hooks managementInterceptor when security plugins are configured

	ManagementInterceptor.java
		Central interceptor for JMX RMI connector.
		Each JMX call go through interceptor via MBeanServerWrapper in following fashion

		jmx(mxbean.op()) -> mbeanServerWrapper -> interceptor -> security plugin -> back to wrapper -> mxbean.op()

	ResourceOperationContext
		OperationContext for all m&m resource operations.
		This returns operation code as RESOURCE (except for data commands) and has additional code called resourceOperationCode which return exact operation requested

	ResourceOperation
		This annotation is used to mark mxbean interfaces and commands to corresponding m&m action

	JMXOperationContext
		describes mbean operation(getAttr,SetAttr,Op) in terms of ResourceOperationContext.
		Parses all MXBean annotation and build map used for mapping jmx calls to resource codes
	CLIOperationContext
		describes gfsh command(name, params) in terms of ResourceOperationContext
		Parses all Command annotation and build map used for mapping gfsh command calls to resource codes

	*MXBean and *Commands Changes
		Added ResourceOperation annotation

REST ADMIN - Key Changes

	AuthManager
		gateway to authorize and authenticate REST ADMIN

	internal/web/controllers/AbstractCommandsController.java
		Changes for ADMIN REST to add authentication and authorization callbacks

Pulse - Key Changes from gemfire side

	AccessControlMXBean/AccessControlContext
		This is hidden mbean which opens up authorization end-point for Pulse
		Pulse will access this mbean to know its authorization levels after connecting with given credentials
		Any JMX Client can use this mbean to know its (currrent jmx connection) authorization levels

REST - Key changes

	gemfire-web-api - AbstractBaseController.java and other controller classes
		REST API changes for At & Az

	DistributionConfig (its impl)
		New system properties token-service for REST

	TokenService
		New interface for REST endpoint which is supposed to give secured token when given Princial

	RestAPIsOperationContext
		OperationContext for REST API


Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/d511979e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/d511979e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/d511979e

Branch: refs/heads/feature/GEODE-17
Commit: d511979efbbbd8146f1bd285a4642df87b0a29bb
Parents: e040750
Author: tushark <tu...@apache.org>
Authored: Thu Aug 27 14:58:02 2015 +0530
Committer: tushark <tu...@apache.org>
Committed: Thu Aug 27 14:58:02 2015 +0530

----------------------------------------------------------------------
 .../cache/operations/OperationContext.java      |  70 +-
 .../operations/RestAPIsOperationContext.java    |  64 ++
 .../gemfire/distributed/DistributedSystem.java  |  10 +
 .../internal/AbstractDistributionConfig.java    |  21 +
 .../internal/DistributionConfig.java            |  29 +
 .../internal/DistributionConfigImpl.java        |  31 +
 .../gemfire/internal/i18n/LocalizedStrings.java |   3 +-
 .../internal/security/AuthorizeRequest.java     |  12 +
 .../gemfire/management/CacheServerMXBean.java   |  18 +-
 .../gemfire/management/DiskStoreMXBean.java     |  17 +-
 .../management/DistributedSystemMXBean.java     |  16 +-
 .../management/GatewayReceiverMXBean.java       |   5 +
 .../gemfire/management/GatewaySenderMXBean.java |   8 +
 .../gemfire/management/LockServiceMXBean.java   |   4 +
 .../gemfire/management/ManagerMXBean.java       |   7 +
 .../gemfire/management/MemberMXBean.java        |  11 +
 .../management/internal/AuthManager.java        | 296 ++++++
 .../management/internal/ManagementAgent.java    |  14 +-
 .../gemfire/management/internal/RestAgent.java  | 151 ++-
 .../internal/SystemManagementService.java       |  10 +-
 .../internal/cli/commands/ClientCommands.java   |   7 +-
 .../internal/cli/commands/ConfigCommands.java   |   6 +
 .../CreateAlterDestroyRegionCommands.java       |   6 +
 .../internal/cli/commands/DataCommands.java     |   4 +-
 .../internal/cli/commands/DeployCommands.java   |   7 +
 .../cli/commands/DiskStoreCommands.java         |  18 +-
 .../cli/commands/DurableClientCommands.java     |   7 +
 ...ExportImportSharedConfigurationCommands.java |   5 +
 .../internal/cli/commands/FunctionCommands.java |   8 +-
 .../internal/cli/commands/GfshHelpCommands.java |   5 +
 .../cli/commands/HDFSStoreCommands.java         |   8 +
 .../internal/cli/commands/IndexCommands.java    |   9 +
 .../cli/commands/LauncherLifecycleCommands.java |  18 +-
 .../internal/cli/commands/MemberCommands.java   |   5 +
 .../cli/commands/MiscellaneousCommands.java     |  11 +-
 .../internal/cli/commands/PDXCommands.java      |   5 +
 .../internal/cli/commands/QueueCommands.java    |   5 +
 .../internal/cli/commands/RegionCommands.java   |   5 +
 .../internal/cli/commands/ShellCommands.java    |  49 +-
 .../internal/cli/commands/StatusCommands.java   |   4 +
 .../internal/cli/commands/WanCommands.java      |  15 +
 .../internal/cli/shell/JmxOperationInvoker.java |  64 +-
 .../internal/security/AccessControl.java        |  12 +-
 .../internal/security/AccessControlContext.java |  14 +-
 .../internal/security/AccessControlMXBean.java  |   6 +
 .../internal/security/CLIOperationContext.java  | 236 +++--
 .../internal/security/JMXOperationContext.java  | 357 ++++---
 .../internal/security/JSONAuthorization.java    |   4 +-
 .../internal/security/MBeanServerWrapper.java   | 109 ++-
 .../security/ManagementInterceptor.java         | 495 ++++++----
 .../management/internal/security/Resource.java  |   9 +-
 .../internal/security/ResourceConstants.java    | 105 +-
 .../internal/security/ResourceOperation.java    |   6 +
 .../security/ResourceOperationContext.java      | 588 +++++++----
 .../security/SetAttributesOperationContext.java |  39 +
 .../controllers/AbstractCommandsController.java | 105 +-
 .../controllers/ConfigCommandsController.java   |  14 +-
 .../web/controllers/DataCommandsController.java |  18 +-
 .../DiskStoreCommandsController.java            |  11 +-
 .../controllers/FunctionCommandsController.java |   7 +-
 .../MiscellaneousCommandsController.java        |   8 +-
 .../web/controllers/WanCommandsController.java  |   2 +-
 .../controllers/WanCommandsController.java.rej  |  10 +
 .../EnvironmentVariablesHandlerInterceptor.java |  86 ++
 .../web/http/support/SimpleHttpRequester.java   | 105 +-
 .../web/shell/AbstractHttpOperationInvoker.java |  33 +-
 .../web/shell/RestHttpOperationInvoker.java     |  26 +-
 .../web/shell/SimpleHttpOperationInvoker.java   |  11 +-
 .../gemfire/security/GeodeTokenService.java     | 101 ++
 .../gemstone/gemfire/security/TokenService.java |  60 ++
 .../extension/mock/MockExtensionCommands.java   |   9 +
 .../internal/cli/CommandManagerJUnitTest.java   |  10 +
 .../internal/cli/GfshParserJUnitTest.java       |  12 +-
 .../shell/GfshExecutionStrategyJUnitTest.java   |   7 +
 .../internal/security/JSONAuthCodeTest.java     |   2 +-
 .../security/ResourceOperationJUnit.java        | 968 +++++++++++++------
 .../internal/web/controllers/RestTestUtils.java |  10 +
 .../web/controllers/AbstractBaseController.java |  34 +-
 .../web/controllers/BaseControllerAdvice.java   |  44 +-
 .../web/controllers/CommonCrudController.java   |  83 +-
 .../controllers/FunctionAccessController.java   |  75 +-
 .../web/controllers/PdxBasedCrudController.java | 118 ++-
 .../web/controllers/QueryAccessController.java  | 139 ++-
 .../web/security/AuthorizationProvider.java     | 295 ++++++
 .../security/FunctionExecutionPostAuthzRC.java  | 101 ++
 .../web/security/RestRequestFilter.java         | 241 +++++
 gemfire-web-api/src/main/webapp/WEB-INF/web.xml |  10 +
 87 files changed, 4661 insertions(+), 1142 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/cache/operations/OperationContext.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/cache/operations/OperationContext.java b/gemfire-core/src/main/java/com/gemstone/gemfire/cache/operations/OperationContext.java
index d25063c..ec0c128 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/cache/operations/OperationContext.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/cache/operations/OperationContext.java
@@ -75,13 +75,49 @@ public abstract class OperationContext {
     
     private static final byte OP_REMOVEALL = 19;
     
+    /**
+    @since Geode 1.0
+    */
     private static final byte OP_RESOURCE = 20;
     
-    private static final OperationCode[] VALUES = new OperationCode[22];
+    private static final byte OP_LIST = 21;
+    
+    private static final byte OP_CREATE_QUERY = 22;
+
+    private static final byte OP_UPDATE_QUERY = 23;
+
+    private static final byte OP_DELETE_QUERY = 24;
+    
+    private static final OperationCode[] VALUES = new OperationCode[25];
 
     private static final Map OperationNameMap = new HashMap();
 
     /**
+     * A LIST operation.
+     * LIST regions, registered functions, named queries in DS. 
+     */
+    public static final OperationCode LIST = new OperationCode(
+        "LIST", OP_LIST);
+    
+    /**
+     * A create parameterized query operation with developer REST APIs. 
+     */
+    public static final OperationCode CREATE_QUERY = new OperationCode(
+        "CREATE_QUERY", OP_CREATE_QUERY);
+    
+    /**
+     * A update parameterized query operation with developer REST APIs. 
+     */
+    public static final OperationCode UPDATE_QUERY = new OperationCode(
+        "UPDATE_QUERY", OP_UPDATE_QUERY);
+    
+    /**
+     * A delete parameterized query operation with developer REST APIs. 
+     */
+    public static final OperationCode DELETE_QUERY = new OperationCode(
+        "DELETE_QUERY", OP_DELETE_QUERY);
+    
+    /**
      * An entry get operation.
      * 
      * @see Region#get(Object)
@@ -223,7 +259,9 @@ public abstract class OperationContext {
     
     
     /**
-     * A resource operation. See ResourceOperationContext for more details
+     * A resource operation 
+     * 
+     * @since Geode 1.0
      */
     public static final OperationCode RESOURCE = new OperationCode(
         "RESOURCE", OP_RESOURCE);
@@ -246,8 +284,36 @@ public abstract class OperationContext {
       VALUES[opCode] = this;
       OperationNameMap.put(name, this);
     }
+    
+    /**
+     * Returns true if this is a list operation for regions, functions and queries.
+     */
+    public boolean isList() {
+      return (this.opCode == OP_LIST);
+    }
+    
+    /**
+     * Returns true if this is a create named query operation.
+     */
+    public boolean isCreateQuery() {
+      return (this.opCode == OP_CREATE_QUERY);
+    }
 
     /**
+     * Returns true if this is a update named query operation.
+     */
+    public boolean isUpdateQuery() {
+      return (this.opCode == OP_UPDATE_QUERY);
+    }
+    
+    /**
+     * Returns true if this is a delete named query operation.
+     */
+    public boolean isDestroyQuery() {
+      return (this.opCode == OP_DELETE_QUERY);
+    }
+    
+    /**
      * Returns true if this is a entry get operation.
      */
     public boolean isGet() {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/cache/operations/RestAPIsOperationContext.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/cache/operations/RestAPIsOperationContext.java b/gemfire-core/src/main/java/com/gemstone/gemfire/cache/operations/RestAPIsOperationContext.java
new file mode 100644
index 0000000..57f56a0
--- /dev/null
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/cache/operations/RestAPIsOperationContext.java
@@ -0,0 +1,64 @@
+/*=========================================================================
+ * Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved.
+ * This product is protected by U.S. and international copyright
+ * and intellectual property laws. Pivotal products are covered by
+ * more patents listed at http://www.pivotal.io/patents.
+ *=========================================================================
+ */
+
+package com.gemstone.gemfire.cache.operations;
+
+
+/**
+ * Encapsulates a REST APIs specific operations for both the pre-operation and
+ * post-operation cases.
+ * 
+ * @author Nilkanth Patel
+ * @since 9.0
+ */
+public class RestAPIsOperationContext extends OperationContext {
+  
+  private boolean restOperation;
+  
+  private OperationCode opCode;
+  
+  private String queryId;
+  private String oqlStatement;
+  
+  public RestAPIsOperationContext( OperationCode opCode, boolean restOperation) {
+    this.opCode = opCode;
+    this.restOperation = restOperation;
+  }
+  
+  public RestAPIsOperationContext( OperationCode opCode, boolean restOperation,
+                                  String queryId, String oqlStatement) {
+    this.opCode = opCode;
+    this.restOperation = restOperation;
+    this.queryId = queryId;
+    this.oqlStatement = oqlStatement;
+  }
+  
+  /**
+   * True if the context is for REST APIs specific operation.
+   */
+  public boolean isRestAPIsOperation() {
+    return this.restOperation;
+  }
+
+  /**
+   * Set the REST APIs specific operation flag to true.
+   */
+  public void setRestAPIsOperation() {
+    this.restOperation = true;
+  }
+
+  @Override
+  public OperationCode getOperationCode() {
+    return this.opCode;
+  }
+
+  @Override
+  public boolean isPostOperation() {
+    return false;
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/DistributedSystem.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/DistributedSystem.java b/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/DistributedSystem.java
index b7b2cd8..bc97c34 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/DistributedSystem.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/DistributedSystem.java
@@ -587,6 +587,16 @@ import com.gemstone.gemfire.security.GemFireSecurityException;
  *   <dd><U>Allowed values</U>: jar file:class name</dd>
  *</dl>
  * 
+ *<dl>
+ *   <a name="security-rest-token-service"><dt>security-rest-token-service</dt></a>
+ *   <dd><U>Description</U>: Token service module name for REST servers that that is 
+ *   required to manage tokens.
+ *   Module must implement TokenService interface.
+ *   </dd>
+ *   <dd><U>Default</U>: ""</dd>
+ *   <dd><U>Allowed values</U>: jar file:class name.method name</dd>
+ *</dl>
+ *
  * <dl>
  * <a name="delta-propagation">
  * <dt>delta-propagation</dt>

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/AbstractDistributionConfig.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/AbstractDistributionConfig.java b/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/AbstractDistributionConfig.java
index 472959d..ce75981 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/AbstractDistributionConfig.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/AbstractDistributionConfig.java
@@ -1122,6 +1122,14 @@ public abstract class AbstractDistributionConfig
     return _modifiableDefault();
   }
 
+  protected void checkSecurityRestTokenService(String value) {
+    _checkIfModifiable(SECURITY_REST_TOKEN_SERVICE_NAME);
+  }
+
+  public boolean isSecurityRestTokenServiceModifiable() {
+    return _modifiableDefault();
+  }
+
   protected void checkSecurityClientDHAlgo(String value) {
     _checkIfModifiable(SECURITY_CLIENT_DHALGO_NAME);
   }
@@ -1586,6 +1594,7 @@ public abstract class AbstractDistributionConfig
       HTTP_SERVICE_SSL_PROTOCOLS_NAME,
       HTTP_SERVICE_SSL_CIPHERS_NAME,
       HTTP_SERVICE_SSL_KEYSTORE_NAME,HTTP_SERVICE_SSL_KEYSTORE_TYPE_NAME,HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME,HTTP_SERVICE_SSL_TRUSTSTORE_NAME,HTTP_SERVICE_SSL_TRUSTSTORE_PASSWORD_NAME,
+      SECURITY_REST_TOKEN_SERVICE_NAME,
       OFF_HEAP_MEMORY_SIZE_NAME, 
       LOCK_MEMORY_NAME,
       DISTRIBUTED_TRANSACTIONS_NAME
@@ -1888,6 +1897,8 @@ public abstract class AbstractDistributionConfig
       this.setHttpServiceSSLTrustStorePassword((String)attValue);
     } else if (attName.equalsIgnoreCase(START_DEV_REST_API_NAME)) {
       this.setStartDevRestApi(((Boolean)attValue).booleanValue());
+    } else if (attName.equalsIgnoreCase(SECURITY_REST_TOKEN_SERVICE_NAME)) {
+      this.setSecurityRestTokenService((String)attValue);
     } else if (attName.equalsIgnoreCase(OFF_HEAP_MEMORY_SIZE_NAME)) {
       this.setOffHeapMemorySize((String)attValue);
     } else if (attName.equalsIgnoreCase(LOCK_MEMORY_NAME)) {
@@ -2178,6 +2189,8 @@ public abstract class AbstractDistributionConfig
       return this.getHttpServiceSSLTrustStorePassword();
     } else if (attName.equalsIgnoreCase(START_DEV_REST_API_NAME)) {
       return this.getStartDevRestApi();
+    } else if (attName.equalsIgnoreCase(SECURITY_REST_TOKEN_SERVICE_NAME)) {
+      return this.getSecurityRestTokenService();
     } else if (attName.equalsIgnoreCase(OFF_HEAP_MEMORY_SIZE_NAME)) {
       return this.getOffHeapMemorySize();
     } else if (attName.equalsIgnoreCase(LOCK_MEMORY_NAME)) {
@@ -2471,6 +2484,8 @@ public abstract class AbstractDistributionConfig
       return this.isHttpServiceSSLTrustStorePasswordModifiable();
     } else if (attName.equalsIgnoreCase(START_DEV_REST_API_NAME)) {
       return this.isStartDevRestApiModifiable();
+    } else if (attName.equalsIgnoreCase(SECURITY_REST_TOKEN_SERVICE_NAME)) {
+      return this.isSecurityRestTokenServiceModifiable();    
     } else if (attName.equalsIgnoreCase(LOCK_MEMORY_NAME)) {
       return this.isLockMemoryModifiable();
     } else if (attName.equals(DISTRIBUTED_TRANSACTIONS_NAME)) {
@@ -2762,6 +2777,8 @@ public abstract class AbstractDistributionConfig
       return String.class;
     } else if (attName.equalsIgnoreCase(START_DEV_REST_API_NAME)) {
       return Boolean.class;
+    } else if (attName.equalsIgnoreCase(SECURITY_REST_TOKEN_SERVICE_NAME)) {
+      return String.class;
     } else if (attName.equalsIgnoreCase(OFF_HEAP_MEMORY_SIZE_NAME)) {
       return String.class;
     } else if (attName.equalsIgnoreCase(LOCK_MEMORY_NAME)) {
@@ -3057,6 +3074,10 @@ public abstract class AbstractDistributionConfig
       LocalizedStrings.AbstractDistributionConfig_SECURITY_CLIENT_AUTHENTICATOR_NAME_0
         .toLocalizedString(DEFAULT_SECURITY_CLIENT_AUTHENTICATOR));
 
+    m.put(SECURITY_REST_TOKEN_SERVICE_NAME, 
+        LocalizedStrings.AbstractDistributionConfig_SECURITY_REST_TOKEN_SERVICE_NAME_0
+          .toLocalizedString(DEFAULT_SECURITY_REST_TOKEN_SERVICE));
+
     m.put(SECURITY_CLIENT_DHALGO_NAME, 
       LocalizedStrings.AbstractDistributionConfig_SECURITY_CLIENT_DHALGO_NAME_0
         .toLocalizedString(DEFAULT_SECURITY_CLIENT_DHALGO));

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfig.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfig.java b/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfig.java
index 10094a9..baa6be5 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfig.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfig.java
@@ -2016,6 +2016,35 @@ public interface DistributionConfig extends Config, LogConfig {
   public static final String DEFAULT_SECURITY_CLIENT_AUTHENTICATOR = "";
 
   /**
+   * Returns user module name generating token in <a
+   * href="../DistributedSystem.html#security-rest-token-service">"security-rest-token-service"</a>
+   */
+  public String getSecurityRestTokenService();
+
+  /**
+   * Sets the user defined method name in <a
+   * href="../DistributedSystem.html#security-rest-token-service">"security-rest-token-service"</a>
+   * property.
+   */
+  public void setSecurityRestTokenService(String attValue);
+
+  /**
+   * Returns true if the value of the token service method name can
+   * currently be modified. Some attributes can not be modified while the
+   * system is running.
+   */
+  public boolean isSecurityRestTokenServiceModifiable();
+
+  /** The name of factory method for "security-rest-token-service" property */
+  public static final String SECURITY_REST_TOKEN_SERVICE_NAME = "security-rest-token-service";
+
+  /**
+   * The default REST token service method name.
+   * <p> Actual value of this is fully qualified <code>"method name"</code>.
+   */
+  public static final String DEFAULT_SECURITY_REST_TOKEN_SERVICE = "";
+
+  /**
    * Returns name of algorithm to use for Diffie-Hellman key exchange <a
    * href="../DistributedSystem.html#security-client-dhalgo">"security-client-dhalgo"</a>
    */

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfigImpl.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfigImpl.java b/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfigImpl.java
index 3707ff3..88b6445 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfigImpl.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionConfigImpl.java
@@ -220,6 +220,9 @@ public class DistributionConfigImpl
   /** The post-processing client authorization method name*/
   private String securityClientAccessorPP = DEFAULT_SECURITY_CLIENT_ACCESSOR_PP;
 
+  /** The token service method name*/
+  private String securityRestTokenService = DEFAULT_SECURITY_REST_TOKEN_SERVICE;
+
   /**
    * The level at which security related log messages are logged
    *
@@ -557,6 +560,9 @@ public class DistributionConfigImpl
     
     this.startDevRestApi = other.getStartDevRestApi();
 
+    // Following added for 8.2
+    this.securityRestTokenService = other.getSecurityRestTokenService();
+
     // following added for 9.0
     this.offHeapMemorySize = other.getOffHeapMemorySize();
     
@@ -1952,6 +1958,10 @@ public class DistributionConfigImpl
     return securityClientAuthenticator;
   }
 
+  public String getSecurityRestTokenService() {
+    return securityRestTokenService;
+  }
+
   public boolean getEnableNetworkPartitionDetection() {
     return this.enableNetworkPartitionDetection;
   }
@@ -1971,6 +1981,11 @@ public class DistributionConfigImpl
     securityClientAuthenticator = value;
   }
 
+  public void setSecurityRestTokenService(String value) {
+    checkSecurityRestTokenService(value);
+    securityRestTokenService = value;
+  }
+
   public String getSecurityClientDHAlgo() {
     return securityClientDHAlgo;
   }
@@ -2851,6 +2866,15 @@ public class DistributionConfigImpl
         return false;
     } else if (!userDefinedProps.equals(other.userDefinedProps))
       return false;
+
+      
+    if (securityRestTokenService == null) {
+      if (other.securityRestTokenService != null)
+        return false;
+    } else if (!securityRestTokenService
+        .equals(other.securityRestTokenService))
+      return false;
+
     return true;
   }
 
@@ -3120,6 +3144,13 @@ public class DistributionConfigImpl
         + ((userCommandPackages == null) ? 0 : userCommandPackages.hashCode());
     result = prime * result
         + ((userDefinedProps == null) ? 0 : userDefinedProps.hashCode());
+
+
+    result = prime
+        * result
+        + ((securityRestTokenService == null) ? 0 : securityRestTokenService
+            .hashCode());
+
     return result;
   }
   

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/internal/i18n/LocalizedStrings.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/i18n/LocalizedStrings.java b/gemfire-core/src/main/java/com/gemstone/gemfire/internal/i18n/LocalizedStrings.java
index f5ae3e5..4a35015 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/i18n/LocalizedStrings.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/internal/i18n/LocalizedStrings.java
@@ -1285,8 +1285,9 @@ public class LocalizedStrings extends ParentLocalizedStrings {
   public static final StringId AuthorizeRequestPP_0_NOT_AUTHORIZED_TO_PERFORM_EXECUTE_REGION_FUNCTION_1= new StringIdImpl(4664, "{0}: In post-process: Not authorized to perform EXECUTE_REGION_FUNCTION operation on region [{1}]");
   public static final StringId PartitionedRegionLoadModel_INCOMPLETE_COLOCATION= new StringIdImpl(4665, "PartitionedRegionLoadModel - member {0} has incomplete colocation, but it has buckets for some regions. Should have colocated regions {1}  but had {2}  and contains buckets {3}");
   public static final StringId HeapMemoryMonitor_OVERRIDDING_MEMORYPOOLMXBEAN_HEAP_0_NAME_1 = new StringIdImpl(4666, "Overridding MemoryPoolMXBean heap threshold bytes {0} on pool {1}");
+  public static final StringId AbstractDistributionConfig_SECURITY_REST_TOKEN_SERVICE_NAME_0 = new StringIdImpl(4667, "User defined fully qualified method name of a class implementing the TokenService interface for REST client verification. Defaults to \"{0}\". Legal values can be any \"method name\" of a static method that is present in the classpath.");
   
-  // 4667-4668 is UNUSED.
+  // 4668 is UNUSED.
   
   public static final StringId MemoryMonitor_MEMBER_ABOVE_CRITICAL_THRESHOLD = new StringIdImpl(4669, "Member: {0} above {1} critical threshold");
   public static final StringId MemoryMonitor_MEMBER_ABOVE_HIGH_THRESHOLD = new StringIdImpl(4670, "Member: {0} above {1} eviction threshold");

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/internal/security/AuthorizeRequest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/security/AuthorizeRequest.java b/gemfire-core/src/main/java/com/gemstone/gemfire/internal/security/AuthorizeRequest.java
index 8ba07a2..364f6be 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/internal/security/AuthorizeRequest.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/internal/security/AuthorizeRequest.java
@@ -93,6 +93,18 @@ public class AuthorizeRequest {
     return this.authzCallback;
   }
 
+  public Principal getPrincipal() {
+    return principal;
+  }
+
+  public boolean isPrincipalSerializable() {
+    return isPrincipalSerializable;
+  }
+
+  public LogWriterI18n getLogger() {
+    return logger;
+  }
+  
   public GetOperationContext getAuthorize(String regionName, Object key,
       Object callbackArg) throws NotAuthorizedException {
 

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/CacheServerMXBean.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/CacheServerMXBean.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/CacheServerMXBean.java
index 59f6537..9e4954d 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/CacheServerMXBean.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/CacheServerMXBean.java
@@ -1,14 +1,9 @@
-/*
- *  =========================================================================
- *  Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved.
- * This product is protected by U.S. and international copyright
- * and intellectual property laws. Pivotal products are covered by
- * more patents listed at http://www.pivotal.io/patents.
- *  ========================================================================
- */
 package com.gemstone.gemfire.management;
 
 import com.gemstone.gemfire.cache.server.CacheServer;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * MBean that provides access to information and management functionality for a
@@ -271,6 +266,7 @@ public interface CacheServerMXBean {
    * @param indexName
    *          Name of the index to be removed.
    */
+  @ResourceOperation(resource=Resource.REGION, operation=ResourceConstants.DESTROY_INDEX)
   public void removeIndex(String indexName) throws Exception;
 
   /**
@@ -287,7 +283,8 @@ public interface CacheServerMXBean {
    * target cache server - other copies of the CQ on other servers are
    * not affected. Using the client side CQ methods to modify a CQ.
    */
-  @Deprecated 
+  @Deprecated
+  @ResourceOperation(resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.QUERY)
   public void executeContinuousQuery(String queryName) throws Exception;
 
   /**
@@ -301,6 +298,7 @@ public interface CacheServerMXBean {
    * not affected. Using the client side CQ methods to modify a CQ.         
    */
   @Deprecated
+  @ResourceOperation(resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.STOP_CONTINUOUS_QUERY)
   public void stopContinuousQuery(String queryName) throws Exception;
 
   /**
@@ -313,6 +311,7 @@ public interface CacheServerMXBean {
    * not affected. Using the client side CQ methods to modify a CQ.         
    */
   @Deprecated
+  @ResourceOperation(resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.STOP_CONTINUOUS_QUERY)
   public void closeAllContinuousQuery(String regionName) throws Exception;
   
   
@@ -326,6 +325,7 @@ public interface CacheServerMXBean {
    * not affected. Using the client side CQ methods to modify a CQ.         
    */
   @Deprecated
+  @ResourceOperation(resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.STOP_CONTINUOUS_QUERY)
   public void closeContinuousQuery(String queryName) throws Exception;
 
 

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/DiskStoreMXBean.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/DiskStoreMXBean.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/DiskStoreMXBean.java
index f14d16c..cf2ea91 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/DiskStoreMXBean.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/DiskStoreMXBean.java
@@ -1,14 +1,9 @@
-/*
- *  =========================================================================
- *  Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved.
- * This product is protected by U.S. and international copyright
- * and intellectual property laws. Pivotal products are covered by
- * more patents listed at http://www.pivotal.io/patents.
- *  ========================================================================
- */
 package com.gemstone.gemfire.management;
 
 import com.gemstone.gemfire.cache.DiskStore;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 
 /**
@@ -149,6 +144,7 @@ public interface DiskStoreMXBean {
    * compaction is true then the application will wait for the other op-logs to
    * be compacted and additional space is available.
    */
+  @ResourceOperation(resource=Resource.DISKSTORE, operation=ResourceConstants.FORCE_ROLL)
   public void forceRoll();
 
   /**
@@ -162,12 +158,14 @@ public interface DiskStoreMXBean {
    *         that no op-logs were ready to be compacted or that a compaction was
    *         already in progress.
    */
+  @ResourceOperation(resource=Resource.DISKSTORE, operation=ResourceConstants.FORCE_COMPACTION)
   public boolean forceCompaction();
   
   /**
    * Causes any data that is currently in the asynchronous queue to be written
    * to disk. Does not return until the flush is complete.
    */
+  @ResourceOperation(resource=Resource.DISKSTORE, operation=ResourceConstants.FLUSH_DISKSTORE)
   public void flush();
 
   /**
@@ -193,6 +191,7 @@ public interface DiskStoreMXBean {
    * 
    * @param warningPercent the warning percent
    */
+  @ResourceOperation(resource=Resource.DISKSTORE, operation=ResourceConstants.SET_DISK_USAGE)
   public void setDiskUsageWarningPercentage(float warningPercent);
   
   /**
@@ -200,5 +199,7 @@ public interface DiskStoreMXBean {
    * 
    * @param criticalPercent the critical percent
    */
+  @ResourceOperation(resource=Resource.DISKSTORE, operation=ResourceConstants.SET_DISK_USAGE)
   public void setDiskUsageCriticalPercentage(float criticalPercent);
+  
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/DistributedSystemMXBean.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/DistributedSystemMXBean.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/DistributedSystemMXBean.java
index f0a0a79..6ac2556 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/DistributedSystemMXBean.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/DistributedSystemMXBean.java
@@ -153,7 +153,7 @@ public interface DistributedSystemMXBean {
    *          Minimum level for alerts to be delivered.
    *          Must be one of: WARNING, ERROR, SEVERE or NONE.
    */
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.CHANGE_ALERT_LEVEL_DS) 
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.CHANGE_ALERT_LEVEL) 
   public void changeAlertLevel(String alertLevel) throws Exception;
 
   /**
@@ -236,7 +236,7 @@ public interface DistributedSystemMXBean {
    *          path of the directory for baseline backup.
    * @return The results of the backup request.
    */
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.BACKUP_DS)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.BACKUP_MEMBERS)
   public DiskBackupStatus backupAllMembers(String targetDirPath, String baselineDirPath)
       throws Exception;
 
@@ -321,7 +321,7 @@ public interface DistributedSystemMXBean {
    *
    * @return List of names of all distributed members that were shutdown.
    */
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.SHUTDOWN_DS)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.SHUTDOWN)
   public String[] shutDownAllMembers() throws Exception;
 
   /**
@@ -341,7 +341,7 @@ public interface DistributedSystemMXBean {
    *          UUID of the disk store to remove
    * @return True if the request is successful, false otherwise.
    */
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.REMOVE_DISKSTORE_DS)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.REVOKE_MISSING_DISKSTORE)
   public boolean revokeMissingDiskStores(String diskStoreId)
       throws Exception;
 
@@ -617,7 +617,7 @@ public interface DistributedSystemMXBean {
    *          will be set.
    * @return a JSON formated string containing data and its type
    */
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.QUERYDATA_DS)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.QUERY)
   public String queryData(String queryString, String members, int limit) throws Exception;
   
   /**
@@ -647,7 +647,7 @@ public interface DistributedSystemMXBean {
    *          will be set.
    * @return a byte[] which is a compressed JSON string.
    */
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.QUERYDATA_DS)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.QUERY)
   public byte[] queryDataForCompressedResult(String queryString, String members, int limit) throws Exception;
   
   
@@ -673,7 +673,7 @@ public interface DistributedSystemMXBean {
    */
   public int getQueryResultSetLimit();
 
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.QUERYDATA_DS)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.QUERY)
   public void setQueryResultSetLimit(int queryResultSetLimit);
 
   /**
@@ -683,6 +683,6 @@ public interface DistributedSystemMXBean {
    */
   public int getQueryCollectionsDepth();
 
-  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.QUERYDATA_DS)
+  @ResourceOperation( resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.QUERY)
   public void setQueryCollectionsDepth(int queryCollectionsDepth);
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewayReceiverMXBean.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewayReceiverMXBean.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewayReceiverMXBean.java
index 3e5ba1a..bd58598 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewayReceiverMXBean.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewayReceiverMXBean.java
@@ -9,6 +9,9 @@
 package com.gemstone.gemfire.management;
 
 import com.gemstone.gemfire.cache.wan.GatewayReceiver;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * MBean that provides access to information and management functionality for a
@@ -81,11 +84,13 @@ public interface GatewayReceiverMXBean {
   /**
    * Starts the gateway receiver.
    */
+  @ResourceOperation(resource=Resource.GATEWAY_RECEIVER, operation=ResourceConstants.START_GW_RECEIVER)
   public void start() throws Exception;
 
   /**
    * Stops the gateway receiver.
    */
+  @ResourceOperation(resource=Resource.GATEWAY_RECEIVER, operation=ResourceConstants.STOP_GW_RECEIVER)
   public void stop() throws Exception;
 
   /**

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewaySenderMXBean.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewaySenderMXBean.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewaySenderMXBean.java
index b6c5219..44e82b4 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewaySenderMXBean.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/GatewaySenderMXBean.java
@@ -9,6 +9,9 @@
 package com.gemstone.gemfire.management;
 
 import com.gemstone.gemfire.cache.wan.GatewaySender;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * MBean that provides access to information and management functionality for a
@@ -163,26 +166,31 @@ public interface GatewaySenderMXBean {
    * configuration cannot be changed.
    * 
    */
+  @ResourceOperation(resource=Resource.GATEWAY_SENDER, operation=ResourceConstants.START_GW_SENDER)
   public void start();
 
   /**
    * Stops this GatewaySender.
    */
+  @ResourceOperation(resource=Resource.GATEWAY_SENDER, operation=ResourceConstants.STOP_GW_SENDER)
   public void stop();
 
   /**
    * Pauses this GatewaySender.
    */
+  @ResourceOperation(resource=Resource.GATEWAY_SENDER, operation=ResourceConstants.PAUSE_GW_SENDER)
   public void pause();
 
   /**
    * Resumes this paused GatewaySender.
    */
+  @ResourceOperation(resource=Resource.GATEWAY_SENDER, operation=ResourceConstants.RESUME_GW_SENDER)
   public void resume();
 
   /**
    * Rebalances this GatewaySender.
    */
+  @ResourceOperation(resource=Resource.GATEWAY_SENDER, operation=ResourceConstants.LOAD_BALANCE_GW_SENDER)
   public void rebalance();
   
   /**

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/LockServiceMXBean.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/LockServiceMXBean.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/LockServiceMXBean.java
index e53d50a..14b7e09 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/LockServiceMXBean.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/LockServiceMXBean.java
@@ -11,6 +11,9 @@ package com.gemstone.gemfire.management;
 import java.util.Map;
 
 import com.gemstone.gemfire.distributed.internal.locks.DLockService;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * MBean that provides access to information and management functionality for a
@@ -61,6 +64,7 @@ public interface LockServiceMXBean {
   /**
    * Requests that this member become the granter.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.BECOME_LOCK_GRANTOR)
   public void becomeLockGrantor();
 
   /**

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/ManagerMXBean.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/ManagerMXBean.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/ManagerMXBean.java
index 04fda7e..be4dd37 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/ManagerMXBean.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/ManagerMXBean.java
@@ -11,6 +11,9 @@ package com.gemstone.gemfire.management;
 import javax.management.JMException;
 
 import com.gemstone.gemfire.management.internal.Manager;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 
 /**
@@ -35,6 +38,7 @@ public interface ManagerMXBean {
    * 
    * @return True if the manager service was successfully started, false otherwise.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.START_MANAGER)
   public boolean start() throws JMException;
 
   /**
@@ -42,6 +46,7 @@ public interface ManagerMXBean {
    * 
    * @return True if the manager service was successfully stopped, false otherwise.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.STOP_MANAGER)
   public boolean stop() throws JMException;
 
   /**
@@ -55,6 +60,7 @@ public interface ManagerMXBean {
    * @param pulseURL
    *          The URL for the Pulse application.
    */
+  @ResourceOperation(resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public void setPulseURL(String pulseURL);
 
   /**
@@ -71,5 +77,6 @@ public interface ManagerMXBean {
    * @param message
    *          The status message.
    */
+  @ResourceOperation(resource=Resource.DISTRIBUTED_SYSTEM, operation=ResourceConstants.LIST_DS)
   public void setStatusMessage(String message);
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/MemberMXBean.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/MemberMXBean.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/MemberMXBean.java
index e935fcd..941d54b 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/MemberMXBean.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/MemberMXBean.java
@@ -11,6 +11,9 @@ package com.gemstone.gemfire.management;
 import java.util.Map;
 
 import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 
 /**
@@ -137,6 +140,7 @@ public interface MemberMXBean {
    * @param numberOfLines
    *          Number of lines to return, up to a maximum of 100.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.SHOW_LOG)
   public String showLog(int numberOfLines);
 
   /**
@@ -152,6 +156,7 @@ public interface MemberMXBean {
    * 
    * @return A list of names of the disk stores that were compacted.
    */
+  @ResourceOperation(resource=Resource.DISKSTORE, operation=ResourceConstants.COMPACT_DISKSTORE)
   public String[] compactAllDiskStores();
   
   /**
@@ -159,12 +164,14 @@ public interface MemberMXBean {
    * 
    * @return True if the Manager MBean was successfully create, false otherwise.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.CREATE_MANAGER)
   public boolean createManager();
   
   /**
    * Shuts down the member. This is an asynchronous call and it will 
    * return immediately without waiting for a result.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.SHUTDOWN)
   public void shutDownMember();
   
   /**
@@ -185,6 +192,7 @@ public interface MemberMXBean {
    * 
    * @return Result of the execution in JSON format.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.LIST_DS)
   String processCommand(String commandString);
   
   /**
@@ -196,6 +204,7 @@ public interface MemberMXBean {
    *          Environmental properties to use during command execution.
    * @return Result of the execution in JSON format.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.LIST_DS)
   String processCommand(String commandString, Map<String, String> env);
   
   /**
@@ -209,6 +218,7 @@ public interface MemberMXBean {
    *          Binary data specific to the command being executed.
    * @return Result of the execution in JSON format.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.LIST_DS)
   String processCommand(String commandString, Map<String, String> env, Byte[][] binaryData);
 
   /**
@@ -265,6 +275,7 @@ public interface MemberMXBean {
   /**
    * Returns the status.
    */
+  @ResourceOperation(resource=Resource.MEMBER, operation=ResourceConstants.LIST_DS)
   public String status();
 
   /**

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AuthManager.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AuthManager.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AuthManager.java
new file mode 100644
index 0000000..fb68c29
--- /dev/null
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AuthManager.java
@@ -0,0 +1,296 @@
+/*=========================================================================
+ * Copyright (c) 2002-2014 Pivotal Software, Inc. All Rights Reserved.
+ * This product is protected by U.S. and international copyright
+ * and intellectual property laws. Pivotal products are covered by
+ * more patents listed at http://www.pivotal.io/patents.
+ *=========================================================================
+ */
+
+package com.gemstone.gemfire.management.internal;
+
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.ACCESS_DENIED_MESSAGE;
+
+import java.lang.reflect.Method;
+import java.security.Principal;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
+
+import com.gemstone.gemfire.GemFireConfigException;
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.operations.OperationContext;
+import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.distributed.DistributedSystem;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.i18n.LogWriterI18n;
+import com.gemstone.gemfire.internal.ClassLoadUtil;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.logging.InternalLogWriter;
+import com.gemstone.gemfire.security.AccessControl;
+import com.gemstone.gemfire.security.AuthenticationFailedException;
+import com.gemstone.gemfire.security.AuthenticationRequiredException;
+import com.gemstone.gemfire.security.Authenticator;
+import com.gemstone.gemfire.internal.lang.StringUtils;
+
+
+/**
+ * This class acts as a single gateway to authorize and authenticate REST ADMIN
+ * APIS. This stores credentials against CommandAuthZRequest object which is
+ * used to identify a particular client. As REST requests are state less we need
+ * to store this map to avoid re-authenticating same client on subsequent
+ * requests. However this map needs to be purged and cleaned up on some expiry
+ * policy.
+ * 
+ * 
+ * @author rishim
+ *
+ */
+public class AuthManager {
+
+  private Map<Properties, CommandAuthZRequest> authMap = new ConcurrentHashMap<Properties, CommandAuthZRequest>();
+
+  private Cache cache;
+
+  private final LogWriterI18n logger;
+  
+  private long DEFAULT_EXPIRY_TIME = 30; // in minutes
+  
+  private long EXPIRY_TIME ;
+  
+  String authzFactoryName;
+  
+  String postAuthzFactoryName;
+  
+  public static String EXPIRY_TIME_FOR_REST_ADMIN_AUTH = "gemfire.expriyTimeForRESTAdminAuth";
+
+  public AuthManager(Cache cache) {
+    this.cache = cache;
+    this.logger = cache.getSecurityLoggerI18n();    
+    this.EXPIRY_TIME = Long.getLong(EXPIRY_TIME_FOR_REST_ADMIN_AUTH, DEFAULT_EXPIRY_TIME);
+    DistributedSystem system = cache.getDistributedSystem();
+    Properties sysProps = system.getProperties();
+    this.authzFactoryName = sysProps.getProperty(DistributionConfig.SECURITY_CLIENT_ACCESSOR_NAME);
+    this.postAuthzFactoryName = sysProps.getProperty(DistributionConfig.SECURITY_CLIENT_ACCESSOR_PP_NAME);
+  }
+
+  private Authenticator getAuthenticator(String authenticatorMethod, Properties securityProperties,
+      InternalLogWriter logWriter, InternalLogWriter securityLogWriter) throws AuthenticationFailedException {
+    Authenticator auth;
+    try {
+
+      Method instanceGetter = ClassLoadUtil.methodFromName(authenticatorMethod);
+      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(securityProperties, logWriter, securityLogWriter);
+    return auth;
+
+  }
+
+  public void verifyCredentials(Properties credentials) {
+
+    DistributedSystem system = this.cache.getDistributedSystem();
+    Properties sysProps = system.getProperties();
+    String authenticator = sysProps.getProperty(DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME);
+    
+    if (authenticator != null && authenticator.length() > 0) {
+      
+      CommandAuthZRequest authZRequest = authMap.get(credentials);
+      
+      if (authZRequest != null && !authZRequest.hasExpired()) {
+        return; //Already existing credentials . Return from here
+        
+      } else {
+        Principal principal = verifyCredentials(authenticator, credentials, system.getSecurityProperties(),
+            (InternalLogWriter) this.cache.getLogger(), (InternalLogWriter) this.cache.getSecurityLogger(), cache
+                .getDistributedSystem().getDistributedMember());
+
+        if(authZRequest != null){ //i.e its an expired credential
+          CommandAuthZRequest expiredAuth = authMap.remove(credentials);
+          try{
+            expiredAuth.close();
+          }catch(Exception e){
+            logger.error(e);//Don't throw an exception , just logs it
+          }          
+        }
+        
+        authZRequest = new CommandAuthZRequest(principal).init();
+        authMap.put(credentials, authZRequest);
+      }
+    }
+
+  }
+  
+  public void expireAllAuthZ() {
+    for (CommandAuthZRequest auth : authMap.values()) {
+      try {
+        auth.close();
+        
+      } catch (Exception e) {
+        logger.error(e);// Don't throw an exception , just log it, as it depends on the user code.
+      }finally{
+        authMap.clear();
+      }
+    }
+  }
+
+  public void authorize(Properties credentials, OperationContext context) {
+
+    if (!StringUtils.isBlank(authzFactoryName)) {
+      CommandAuthZRequest authZRequest = authMap.get(credentials);
+      boolean authorized = authZRequest.authorize(context);
+      if (!authorized)
+        throw new SecurityException(ACCESS_DENIED_MESSAGE);
+    }
+  }
+
+  public void postAuthorize(Properties credentials, OperationContext context) {
+    if (!StringUtils.isBlank(postAuthzFactoryName)) {
+      CommandAuthZRequest authZRequest = authMap.get(credentials);
+      boolean authorized = authZRequest.postAuthorize(context);
+      if (!authorized)
+        throw new SecurityException(ACCESS_DENIED_MESSAGE);
+    }
+
+  }
+
+  private Principal verifyCredentials(String authenticatorMethod, Properties credentials,
+      Properties securityProperties, InternalLogWriter logWriter, InternalLogWriter securityLogWriter,
+      DistributedMember member) throws AuthenticationRequiredException, AuthenticationFailedException {
+
+    Authenticator authenticator = getAuthenticator(authenticatorMethod, securityProperties, logWriter,
+        securityLogWriter);
+    Principal principal;
+
+    try {
+      principal = authenticator.authenticate(credentials, member);
+    } finally {
+      authenticator.close();
+    }
+
+    return principal;
+
+  }
+
+  public class CommandAuthZRequest {
+
+    private Principal principal;
+
+    private AccessControl authzCallback;
+
+    private AccessControl postAuthzCallback;
+    
+    private long initTime = System.currentTimeMillis();
+
+    public CommandAuthZRequest(Principal principal) {
+      this.principal = principal;
+    }
+
+    public boolean authorize(OperationContext context) {
+      if (authzCallback != null) {
+        return authzCallback.authorizeOperation(null, context);
+      }
+      return true; // If no AccessControl is set then always return true
+    }
+
+    public boolean postAuthorize(OperationContext context) {
+      if (postAuthzCallback != null) {
+        return postAuthzCallback.authorizeOperation(null, context);
+      }
+      return true; // If no AccessControl is set then always return true
+    }
+    
+    public boolean hasExpired(){
+      if(System.currentTimeMillis() - initTime >= EXPIRY_TIME * 60 * 1000){
+        return true;
+      }
+      return false;
+    }
+    
+    public void close() {
+      if (authzCallback != null) {
+        authzCallback.close();
+      }
+      if (postAuthzCallback != null) {
+        postAuthzCallback.close();
+      }
+    }
+
+    private CommandAuthZRequest init() {
+      try {
+        if (!StringUtils.isBlank(authzFactoryName)) {
+          Method authzMethod = ClassLoadUtil.methodFromName(authzFactoryName);
+          this.authzCallback = (AccessControl) authzMethod.invoke(null, (Object[]) null);
+          this.authzCallback.init(principal, null, cache);
+        }
+        if (!StringUtils.isBlank(postAuthzFactoryName)) {
+          Method postAuthzMethod = ClassLoadUtil.methodFromName(postAuthzFactoryName);
+          this.postAuthzCallback = (AccessControl) postAuthzMethod.invoke(null, (Object[]) null);
+          this.postAuthzCallback.init(principal, null, cache);
+        }
+      } catch (IllegalAccessException e) {
+        logger.error(e);
+        throw new GemFireConfigException("Error while configuring accesscontrol for rest resource", e);
+      } catch (Exception e) {
+        logger.error(e);
+        throw new GemFireConfigException("Error while configuring accesscontrol for rest resource", e);
+      }
+      return this;
+    }
+
+    public AccessControl getAuthzCallback() {
+      return authzCallback;
+    }
+
+     public AccessControl getPostAuthzCallback() {
+      return postAuthzCallback;
+    }
+
+    @Override
+    public int hashCode() {
+      final int prime = 31;
+      int result = 1;
+      result = prime * result + getOuterType().hashCode();
+      result = prime * result + (int) (initTime ^ (initTime >>> 32));
+      result = prime * result + ((principal == null) ? 0 : principal.hashCode());
+      return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+      if (this == obj)
+        return true;
+      if (obj == null)
+        return false;
+      if (getClass() != obj.getClass())
+        return false;
+      CommandAuthZRequest other = (CommandAuthZRequest) obj;
+      if (!getOuterType().equals(other.getOuterType()))
+        return false;
+      if (initTime != other.initTime)
+        return false;
+      if (principal == null) {
+        if (other.principal != null)
+          return false;
+      } else if (!principal.equals(other.principal))
+        return false;
+      return true;
+    }
+
+    private AuthManager getOuterType() {
+      return AuthManager.this;
+    }
+
+  }
+
+  public Map<Properties, CommandAuthZRequest> getAuthMap() {
+    return this.authMap;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java
index 43bfe73..975bf1b 100755
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java
@@ -268,6 +268,11 @@ public class ManagementAgent {
             // create region to hold query information (queryId, queryString).
             // Added for the developer REST APIs
             RestAgent.createParameterizedQueryRegion();
+            
+            //Rest APIs security
+            if(!StringUtils.isBlank(this.config.SECURITY_CLIENT_AUTHENTICATOR_NAME)){
+              RestAgent.createTokenToAuthzRequestRegion();
+            }
           }
 
           // set true for HTTP service running
@@ -388,9 +393,9 @@ public class ManagementAgent {
     // Environment map. KIRK: why is this declared as HashMap?
     final HashMap<String, Object> env = new HashMap<String, Object>();
 
-    boolean integratedSecEnabled = System.getProperty("resource-authenticator") != null;
+    boolean integratedSecEnabled = isIntegratedSecEnabled();    
     if (integratedSecEnabled) {
-      securityInterceptor = new ManagementInterceptor(logger);
+      securityInterceptor = new ManagementInterceptor((GemFireCacheImpl)CacheFactory.getAnyInstance(), logger);
       env.put(JMXConnectorServer.AUTHENTICATOR, securityInterceptor);
     } else {
       /* Disable the old authenticator mechanism */
@@ -482,6 +487,11 @@ public class ManagementAgent {
     // final Thread clean = new CleanThread(cs);
     // clean.start();
   }
+  
+  private boolean isIntegratedSecEnabled() {    
+    String authenticatorFactoryName = config.getSecurityClientAuthenticator();    
+    return authenticatorFactoryName != null && !authenticatorFactoryName.isEmpty();
+  }
 
   private static class GemFireRMIClientSocketFactory implements RMIClientSocketFactory,
       Serializable {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java
index 74695ee..714e15e 100755
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java
@@ -8,20 +8,29 @@
 
 package com.gemstone.gemfire.management.internal;
 
+import java.security.Principal;
+import java.util.List;
+
 import org.apache.logging.log4j.Logger;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
+import org.springframework.util.Assert;
 
 import com.gemstone.gemfire.cache.AttributesFactory;
+import com.gemstone.gemfire.cache.Cache;
 import com.gemstone.gemfire.cache.CacheFactory;
 import com.gemstone.gemfire.cache.DataPolicy;
+import com.gemstone.gemfire.cache.Region;
 import com.gemstone.gemfire.cache.RegionAttributes;
 import com.gemstone.gemfire.cache.Scope;
 import com.gemstone.gemfire.distributed.internal.DistributionConfig;
 import com.gemstone.gemfire.internal.GemFireVersion;
 import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
 import com.gemstone.gemfire.internal.cache.InternalRegionArguments;
+import com.gemstone.gemfire.internal.lang.StringUtils;
 import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.security.AuthorizeRequest;
+import com.gemstone.gemfire.internal.security.AuthorizeRequestPP;
 import com.gemstone.gemfire.management.ManagementService;
 
 /**
@@ -39,7 +48,9 @@ public class RestAgent {
 
   private boolean running = false;
   private final DistributionConfig config;
-
+  
+  public static final String AUTH_METADATA_REGION = "__TokenToAuthzRequest__";
+  
   public RestAgent(DistributionConfig config) {
     this.config = config;
   }
@@ -47,13 +58,70 @@ public class RestAgent {
   public synchronized boolean isRunning() {
     return this.running;
   }
-
-  private boolean isManagementRestServiceRunning(GemFireCacheImpl cache) {
-    final SystemManagementService managementService = (SystemManagementService) ManagementService
-        .getManagementService(cache);
-    return (managementService.getManagementAgent() != null && managementService
-        .getManagementAgent().isHttpServiceRunning());
-
+  
+  private static Cache getCache(){
+    Cache cache = GemFireCacheImpl.getExisting();
+    Assert.state(cache != null, "The Gemfire Cache reference was not properly initialized");
+    return cache;
+  }
+  
+  public static Region<String, List<Object>> getAuthzRegion(final String namePath) {
+    /*
+    return  ValidationUtils.returnValueThrowOnNull(getCache().<String, List<Object>>getRegion(namePath),
+      new GemfireRestException(String.format(" (%1$s) store does not exist!", namePath)));
+    */
+    try{
+      return getCache().getRegion(namePath);
+    }catch(Exception e){
+      throw new RuntimeException("AuthorizeStore does not exist!" + e.getMessage());
+    }
+  }
+  
+  public static AuthorizeRequest getAuthorizeRequest(String token){
+    List<Object> objs  = getAuthzRegion(RestAgent.AUTH_METADATA_REGION).get(token);
+    return (AuthorizeRequest)objs.get(0);
+  }
+  
+  public static AuthorizeRequestPP getAuthorizeRequestPP(String token){
+    List<Object> objs  = getAuthzRegion(RestAgent.AUTH_METADATA_REGION).get(token);
+    return (AuthorizeRequestPP)objs.get(1);
+  }
+  
+  public static Principal getPrincipalForToken(String token){
+    return getAuthorizeRequest(token).getPrincipal();
+  }
+  
+  public static synchronized void removeAuthzEntry(String token){
+    //remove the authzCallback. Note that this does not close() it.
+    getAuthzRegion(AUTH_METADATA_REGION).remove(token);
+  }
+  
+  public static void closeAuthz(String token){
+    //Close the authzCallback
+    try{  
+      AuthorizeRequest authRequest =  getAuthorizeRequest(token);
+      if(authRequest != null) {
+        authRequest.close();
+      }
+      
+      AuthorizeRequestPP authRequestPP =  getAuthorizeRequestPP(token);
+      if(authRequestPP != null) {
+        authRequestPP.close();
+      }
+    } catch(Exception e){
+      logger.error("Cannot close the authzCallback for token {}", token, e);
+    }
+  }
+  
+  public static synchronized void addAuthzEntry(String token, List<Object> authObjects){
+    getAuthzRegion(AUTH_METADATA_REGION).put(token, authObjects);
+  }
+  
+  private boolean isManagementRestServiceRunning(GemFireCacheImpl cache){
+    final SystemManagementService managementService = (SystemManagementService) ManagementService.getManagementService(
+        cache);
+    return ( managementService.getManagementAgent() != null && managementService.getManagementAgent().isHttpServiceRunning());
+    
   }
 
   public synchronized void start(GemFireCacheImpl cache) {
@@ -67,8 +135,12 @@ public class RestAgent {
         // create region to hold query information (queryId, queryString). Added
         // for the developer REST APIs
         RestAgent.createParameterizedQueryRegion();
-
-      } catch (RuntimeException e) {
+        
+        if(!StringUtils.isBlank(this.config.SECURITY_CLIENT_AUTHENTICATOR_NAME)){
+          RestAgent.createTokenToAuthzRequestRegion();
+        }
+        
+      } catch (RuntimeException e){
         logger.debug(e.getMessage(), e);
       }
     }
@@ -88,7 +160,21 @@ public class RestAgent {
       }
     }
   }
-
+  
+  public synchronized void cleanup(){
+    //close all authzCallback instances currently present in the region;
+    if(!StringUtils.isBlank(this.config.SECURITY_CLIENT_AUTHENTICATOR_NAME)){
+      for(final String key : getAuthzRegion(AUTH_METADATA_REGION).keySet() ){
+        try{
+          closeAuthz(key);
+          
+        }catch(Exception e){
+          logger.error("Cannot close the authzCallback for token {}", key, e);
+        }
+      }
+    }
+  }
+  
   private Server httpServer;
   private final String GEMFIRE_VERSION = GemFireVersion.getGemFireVersion();
   private AgentUtil agentUtil = new AgentUtil(GEMFIRE_VERSION);
@@ -198,7 +284,48 @@ public class RestAgent {
       } else {
         logger.error("Cannot create ParameterizedQueries Region as no cache found!");
       }
-    } catch (Exception e) {
+    }
+    catch (Exception e) {
+      if (logger.isDebugEnabled()) {
+        logger.debug("Error creating __ParameterizedQueries__ Region with cause {}",e.getMessage(), e);
+      }
+    }
+  }
+  
+  /**
+   * This method will create a REPLICATED region named _ParameterizedQueries__.
+   * In developer REST APIs, this region will be used to store the queryId and queryString as a key and value respectively.
+   */
+  public static void createTokenToAuthzRequestRegion(){
+    try {
+      if (logger.isDebugEnabled()) {
+        logger.debug("Starting creation of  ({}) region", AUTH_METADATA_REGION);
+      }
+      GemFireCacheImpl cache = (GemFireCacheImpl)CacheFactory.getAnyInstance();
+      if (cache != null) {
+        //cache.getCacheConfig().setPdxReadSerialized(true);
+        final InternalRegionArguments regionArguments = new InternalRegionArguments();
+        regionArguments.setIsUsedForMetaRegion(true);
+        final AttributesFactory<String, List<Object>> attributesFactory = new AttributesFactory<String, List<Object>>();
+
+        attributesFactory.setConcurrencyChecksEnabled(false);
+        attributesFactory.setDataPolicy(DataPolicy.NORMAL);
+        attributesFactory.setKeyConstraint(String.class);
+        attributesFactory.setScope(Scope.LOCAL);
+        attributesFactory.setStatisticsEnabled(false);
+        //attributesFactory.setValueConstraint(AuthorizeRequest.class);
+
+        final RegionAttributes<String, List<Object>> regionAttributes = attributesFactory.create();
+        
+        cache.createVMRegion(AUTH_METADATA_REGION, regionAttributes, regionArguments);
+        if (logger.isDebugEnabled()) {
+          logger.debug("Successfully created ({}) region", AUTH_METADATA_REGION);
+        }
+      }else {
+        logger.error("Cannot create ({}) Region as no cache found!", AUTH_METADATA_REGION);
+      }
+    }
+    catch (Exception e) {
       if (logger.isDebugEnabled()) {
         logger.debug("Error creating __ParameterizedQueries__ Region with cause {}",
             e.getMessage(), e);

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/SystemManagementService.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/SystemManagementService.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/SystemManagementService.java
index d8f6983..64a057c 100755
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/SystemManagementService.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/SystemManagementService.java
@@ -121,6 +121,8 @@ public final class SystemManagementService extends BaseManagementService {
    * GemFire comes with a default aggregator. 
    */
   private List<ProxyListener> proxyListeners;
+  
+  private AuthManager authManager;
 
 
   private UniversalListenerContainer universalListenerContainer = new UniversalListenerContainer();
@@ -171,6 +173,7 @@ public final class SystemManagementService extends BaseManagementService {
       this.listener = new ManagementMembershipListener(this);
       system.getDistributionManager().addMembershipListener(listener);
       isStarted = true;
+      this.authManager = new AuthManager(cache);
       return this;
     } catch (CancelException e) {
       // Rethrow all CancelExceptions (fix for defect 46339)
@@ -262,7 +265,8 @@ public final class SystemManagementService extends BaseManagementService {
       }
       if (this.agent != null && this.agent.isRunning()) {
         this.agent.stopAgent();
-      }     
+      }
+      this.authManager.expireAllAuthZ();
       getGemFireCacheImpl().getJmxManagerAdvisor().broadcastChange();
       instances.remove(cache);
       localManager  = null;
@@ -826,4 +830,8 @@ public final class SystemManagementService extends BaseManagementService {
   public void removeMembershipListener(MembershipListener listener) {
     universalListenerContainer.removeMembershipListener(listener);    
   }
+  
+  public AuthManager getAuthManager(){
+    return this.authManager;
+  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ClientCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ClientCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ClientCommands.java
index 2eb1318..958df80 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ClientCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ClientCommands.java
@@ -44,6 +44,9 @@ import com.gemstone.gemfire.management.internal.cli.result.CompositeResultData.S
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * 
@@ -59,6 +62,7 @@ public class ClientCommands implements CommandMarker {
 
   @CliCommand(value = CliStrings.LIST_CLIENTS, help = CliStrings.LIST_CLIENT__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_LIST })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result listClient() {
     Result result = null;
 
@@ -142,6 +146,7 @@ public class ClientCommands implements CommandMarker {
   
   @CliCommand(value = CliStrings.DESCRIBE_CLIENT, help = CliStrings.DESCRIBE_CLIENT__HELP)
   @CliMetaData(relatedTopic = { CliStrings.TOPIC_LIST })
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result describeClient(
       @CliOption(key = CliStrings.DESCRIBE_CLIENT__ID, mandatory = true, help = CliStrings.DESCRIBE_CLIENT__ID__HELP) String clientId) {
     Result result = null;   
@@ -310,7 +315,7 @@ public class ClientCommands implements CommandMarker {
   }
 
   @CliAvailabilityIndicator({ CliStrings.LIST_CLIENTS , CliStrings.DESCRIBE_CLIENT})
-  public boolean functionCommandsAvailable() {
+  public boolean clientCommandsAvailable() {
     boolean isAvailable = true; // always available on server
     if (CliUtil.isGfshVM()) { // in gfsh check if connected
       isAvailable = getGfsh() != null && getGfsh().isConnectedAndReady();

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ConfigCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ConfigCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ConfigCommands.java
index 279fb45..1341890 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ConfigCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ConfigCommands.java
@@ -54,6 +54,9 @@ import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
 import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 /****
  *
  * @author David Hoots
@@ -72,6 +75,7 @@ public class ConfigCommands implements CommandMarker {
 
   @CliCommand(value = { CliStrings.DESCRIBE_CONFIG }, help = CliStrings.DESCRIBE_CONFIG__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = {CliStrings.TOPIC_GEMFIRE_CONFIG})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public Result describeConfig(
       @CliOption (key = CliStrings.DESCRIBE_CONFIG__MEMBER,
       optionContext = ConverterHint.ALL_MEMBER_IDNAME,
@@ -185,6 +189,7 @@ public class ConfigCommands implements CommandMarker {
    */
   @CliCommand(value = { CliStrings.EXPORT_CONFIG }, help = CliStrings.EXPORT_CONFIG__HELP)
   @CliMetaData(interceptor = "com.gemstone.gemfire.management.internal.cli.commands.ConfigCommands$Interceptor", relatedTopic = {CliStrings.TOPIC_GEMFIRE_CONFIG})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.EXPORT_CONFIG)
   public Result exportConfig(
       @CliOption(key = { CliStrings.EXPORT_CONFIG__MEMBER },
                  optionContext = ConverterHint.ALL_MEMBER_IDNAME,
@@ -240,6 +245,7 @@ public class ConfigCommands implements CommandMarker {
 
   @CliCommand(value = { CliStrings.ALTER_RUNTIME_CONFIG }, help = CliStrings.ALTER_RUNTIME_CONFIG__HELP)
   @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEMFIRE_CONFIG})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.ALTER_RUNTIME)
   public Result alterRuntimeConfig(
       @CliOption (key = {CliStrings.ALTER_RUNTIME_CONFIG__MEMBER},
       optionContext = ConverterHint.ALL_MEMBER_IDNAME,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
index 919d6fe..2362b96 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
@@ -75,6 +75,9 @@ import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.cli.util.RegionPath;
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
 import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
 
 /**
  * 
@@ -101,6 +104,7 @@ public class CreateAlterDestroyRegionCommands extends AbstractCommandsSupport {
 
   @CliCommand (value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP)
   @CliMetaData (relatedTopic = CliStrings.TOPIC_GEMFIRE_REGION, writesToSharedConfiguration = true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.CREATE_REGION)
   public Result createRegion(
       @CliOption (key = CliStrings.CREATE_REGION__REGION,
                   mandatory = true,
@@ -432,6 +436,7 @@ public class CreateAlterDestroyRegionCommands extends AbstractCommandsSupport {
   
   @CliCommand (value = CliStrings.ALTER_REGION, help = CliStrings.ALTER_REGION__HELP)
   @CliMetaData (relatedTopic = CliStrings.TOPIC_GEMFIRE_REGION, writesToSharedConfiguration = true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.ALTER_REGION)
   public Result alterRegion(
       @CliOption (key = CliStrings.ALTER_REGION__REGION,
                   mandatory = true,
@@ -990,6 +995,7 @@ public class CreateAlterDestroyRegionCommands extends AbstractCommandsSupport {
 
   @CliCommand(value = { CliStrings.DESTROY_REGION }, help = CliStrings.DESTROY_REGION__HELP)
   @CliMetaData(shellOnly = false, relatedTopic = CliStrings.TOPIC_GEMFIRE_REGION, writesToSharedConfiguration = true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.DESTROY_REGION)
   public Result destroyRegion(
       @CliOption(key = CliStrings.DESTROY_REGION__REGION,
           optionContext = ConverterHint.REGIONPATH,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DataCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DataCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DataCommands.java
index 9e60839..f199d30 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DataCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DataCommands.java
@@ -1009,6 +1009,7 @@ public class DataCommands implements CommandMarker {
   @CliMetaData(shellOnly = false, relatedTopic = {
       CliStrings.TOPIC_GEMFIRE_DATA, CliStrings.TOPIC_GEMFIRE_REGION })
   @CliCommand(value = { CliStrings.GET }, help = CliStrings.GET__HELP)
+  @ResourceOperation(resource = Resource.REGION, operation= ResourceConstants.GET)
   public Result get(
       @CliOption(key = { CliStrings.GET__KEY }, mandatory = true, help = CliStrings.GET__KEY__HELP) String key,
       @CliOption(key = { CliStrings.GET__REGIONNAME }, mandatory = true, help = CliStrings.GET__REGIONNAME__HELP, optionContext = ConverterHint.REGIONPATH) String regionPath,
@@ -1111,6 +1112,7 @@ public class DataCommands implements CommandMarker {
   @CliMetaData(shellOnly = false, relatedTopic = {
       CliStrings.TOPIC_GEMFIRE_DATA, CliStrings.TOPIC_GEMFIRE_REGION })
   @CliCommand(value = { CliStrings.REMOVE }, help = CliStrings.REMOVE__HELP)
+  @ResourceOperation(resource = Resource.REGION, operation= ResourceConstants.REMOVE)
   public Result remove(
       @CliOption(key = { CliStrings.REMOVE__KEY }, help = CliStrings.REMOVE__KEY__HELP) String key,
       @CliOption(key = { CliStrings.REMOVE__REGION }, mandatory = true, help = CliStrings.REMOVE__REGION__HELP, optionContext = ConverterHint.REGIONPATH) String regionPath,
@@ -1165,7 +1167,7 @@ public class DataCommands implements CommandMarker {
       CliStrings.TOPIC_GEMFIRE_DATA, CliStrings.TOPIC_GEMFIRE_REGION })
   @MultiStepCommand
   @CliCommand(value = { CliStrings.QUERY }, help = CliStrings.QUERY__HELP)
-  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.QUERYDATA_DS)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.QUERY)
   public Object query(
       @CliOption(key = CliStrings.QUERY__QUERY, help = CliStrings.QUERY__QUERY__HELP, mandatory = true) final String query,
       @CliOption(key = CliStrings.QUERY__STEPNAME, mandatory = false, help = "Stpe name", unspecifiedDefaultValue = CliStrings.QUERY__STEPNAME__DEFAULTVALUE) String stepName,

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DeployCommands.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DeployCommands.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DeployCommands.java
index 4591b53..3d0cacc 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DeployCommands.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/DeployCommands.java
@@ -36,6 +36,10 @@ import com.gemstone.gemfire.management.internal.cli.result.FileResult;
 import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
 import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
 import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationWriter;
+import com.gemstone.gemfire.management.internal.security.Resource;
+import com.gemstone.gemfire.management.internal.security.ResourceConstants;
+import com.gemstone.gemfire.management.internal.security.ResourceOperation;
+
 import org.springframework.shell.core.CommandMarker;
 import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
 import org.springframework.shell.core.annotation.CliCommand;
@@ -67,6 +71,7 @@ public final class DeployCommands extends AbstractCommandsSupport implements Com
    */
   @CliCommand(value = { CliStrings.DEPLOY }, help = CliStrings.DEPLOY__HELP)
   @CliMetaData(interceptor = "com.gemstone.gemfire.management.internal.cli.commands.DeployCommands$Interceptor", relatedTopic={CliStrings.TOPIC_GEMFIRE_CONFIG}, writesToSharedConfiguration=true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.DEPLOY)
   public final Result deploy(
     @CliOption(key = { CliStrings.DEPLOY__GROUP }, help = CliStrings.DEPLOY__GROUP__HELP, optionContext=ConverterHint.MEMBERGROUP)
     @CliMetaData (valueSeparator = ",")
@@ -149,6 +154,7 @@ public final class DeployCommands extends AbstractCommandsSupport implements Com
    */
   @CliCommand(value = { CliStrings.UNDEPLOY }, help = CliStrings.UNDEPLOY__HELP)
   @CliMetaData(relatedTopic={CliStrings.TOPIC_GEMFIRE_CONFIG}, writesToSharedConfiguration=true)
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.UNDEPLOY)
   public final Result undeploy(
       @CliOption(key = { CliStrings.UNDEPLOY__GROUP },
                  help = CliStrings.UNDEPLOY__GROUP__HELP, 
@@ -219,6 +225,7 @@ public final class DeployCommands extends AbstractCommandsSupport implements Com
    */
   @CliCommand(value = { CliStrings.LIST_DEPLOYED }, help = CliStrings.LIST_DEPLOYED__HELP)
   @CliMetaData(relatedTopic={CliStrings.TOPIC_GEMFIRE_CONFIG})
+  @ResourceOperation(resource = Resource.DISTRIBUTED_SYSTEM, operation= ResourceConstants.LIST_DS)
   public final Result listDeployed(
       @CliOption(key = { CliStrings.LIST_DEPLOYED__GROUP },
                  help = CliStrings.LIST_DEPLOYED__GROUP__HELP)


[4/6] incubator-geode git commit: GEODE-77 : Integrated Security Code Merge Review board url : https://reviews.apache.org/r/37209/

Posted by tu...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/CLIOperationContext.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/CLIOperationContext.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/CLIOperationContext.java
index b0198e4..f5a101d 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/CLIOperationContext.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/CLIOperationContext.java
@@ -7,116 +7,164 @@ import java.util.Map;
 
 import org.springframework.shell.event.ParseResult;
 
-import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.GemFireConfigException;
 import com.gemstone.gemfire.management.cli.CommandProcessingException;
 import com.gemstone.gemfire.management.internal.cli.CommandManager;
 import com.gemstone.gemfire.management.internal.cli.GfshParseResult;
 import com.gemstone.gemfire.management.internal.cli.GfshParser;
+import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
 import com.gemstone.gemfire.management.internal.cli.parser.CommandTarget;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.*;
 
-
+/**
+ * It represents command being executed and all passed options and option-values.
+ * ResourceOpCode returned by CLIOperationContext is retrieved from ResourceOperation 
+ * annotation on the target command
+ * 
+ * @author tushark
+ * @since 9.0
+ */
 public class CLIOperationContext extends ResourceOperationContext {
-	
-	private OperationCode code = OperationCode.RESOURCE;
-	private ResourceOperationCode resourceCode = null;
-	private Map<String,String> commandOptions = null;
-	
-	private static Map<String,ResourceOperationCode> commandToCodeMapping = new HashMap<String,ResourceOperationCode>();
-	private static CommandManager commandManager = null;
-	private static GfshParser parser = null;	
-	
-	public CLIOperationContext(String commandString) throws CommandProcessingException, IllegalStateException{
-		code = OperationCode.RESOURCE;
-		GfshParseResult parseResult = (GfshParseResult) parseCommand(commandString);		
-		this.commandOptions = parseResult.getParamValueStrings();		
-		this.resourceCode = findResourceCode(parseResult.getCommandName()); //need to add this to ParseResult 
-	}
-	
-	private static ParseResult parseCommand(String commentLessLine) throws CommandProcessingException, IllegalStateException {
+  
+  private OperationCode code = OperationCode.RESOURCE;
+  private ResourceOperationCode resourceCode = null;
+  private Map<String,String> commandOptions = null;
+  
+  private static Map<String,ResourceOperationCode> commandToCodeMapping = new HashMap<String,ResourceOperationCode>();
+  private static CommandManager commandManager = null;
+  private static GfshParser parser = null;  
+  
+  public CLIOperationContext(String commandString) throws CommandProcessingException, IllegalStateException{    
+    GfshParseResult parseResult = (GfshParseResult) parseCommand(commandString);    
+    this.commandOptions = parseResult.getParamValueStrings();   
+    this.resourceCode = findResourceCode(parseResult.getCommandName());
+    this.code = findOperationCode(parseResult.getCommandName());
+  }
+  
+  /**
+   * This method returns OperationCode for command. Some commands perform data 
+   * operations, for such commands OperationCode returned is not RESOURCE but
+   * corresponding data operation as defined in OperationCode
+   * 
+   * @param commandName
+   * @return OperationCode
+   */
+  private OperationCode findOperationCode(String commandName) {
+    
+    if(CliStrings.GET.equals(commandName) || CliStrings.LOCATE_ENTRY.equals(commandName))
+      return OperationCode.GET;
+    
+    if(CliStrings.PUT.equals(commandName))
+      return OperationCode.PUT;
+    
+    if(CliStrings.QUERY.equals(commandName))
+      return OperationCode.QUERY;
+    
+    if (CliStrings.REMOVE.equals(commandName)) {
+      if (commandOptions.containsKey(CliStrings.REMOVE__ALL)
+          && "true".equals(commandOptions.get(CliStrings.REMOVE__ALL))) {
+        return OperationCode.REMOVEALL;
+      } else
+        return OperationCode.DESTROY;
+    }
+    
+    if(CliStrings.CLOSE_DURABLE_CQS.equals(commandName)) {
+      return OperationCode.CLOSE_CQ;
+    }
+    
+    if(CliStrings.CREATE_REGION.equals(commandName)) {
+      return OperationCode.REGION_CREATE;
+    }
+    
+    if(CliStrings.DESTROY_REGION.equals(commandName)) {
+      return OperationCode.REGION_DESTROY;
+    }
+    
+    if(CliStrings.EXECUTE_FUNCTION.equals(commandName)) {
+      return OperationCode.EXECUTE_FUNCTION;
+    }
+    
+    //"stop cq"   
+    //"removeall",
+    //"get durable cqs",    
+    return OperationCode.RESOURCE;    
+  }
+
+  private static ParseResult parseCommand(String commentLessLine) throws CommandProcessingException, IllegalStateException {
     if (commentLessLine != null) {
       return parser.parse(commentLessLine);
     }
     throw new IllegalStateException("Command String should not be null.");
   }
-	
-	public static void registerCommand(CommandManager cmdManager, Method method, CommandTarget commandTarget){	  
-	  //Save command manager instance and create a local parser for parsing the commands
-	  if(commandManager==null){
-	    commandManager = cmdManager;
-	    parser = new GfshParser(cmdManager);
-	  }
-	  
-		boolean found=false;
-		Annotation ans[] = method.getDeclaredAnnotations();
-		for(Annotation an : ans){
-			if(an instanceof ResourceOperation) {
-				cache(commandTarget.getCommandName(),(ResourceOperation)an);
-				found=true;
-			}
-		}
-		if(!found)
-			cache(commandTarget.getCommandName(),null);
-	}
+  
+  public static void registerCommand(CommandManager cmdManager, Method method, CommandTarget commandTarget){    
+    if(commandManager==null){
+      commandManager = cmdManager;
+      parser = new GfshParser(cmdManager);
+    }
+    
+    boolean found=false;
+    Annotation ans[] = method.getDeclaredAnnotations();
+    for(Annotation an : ans){
+      if(an instanceof ResourceOperation) {
+        cache(commandTarget.getCommandName(),(ResourceOperation)an);
+        found=true;
+      }
+    }
+    if(!found)
+      cache(commandTarget.getCommandName(),null);
+  }
 
-	private static void cache(String commandName, ResourceOperation op) {
-		ResourceOperationCode code = null;
-		
-		if (op != null) {
-			String opString = op.operation();
-			if (opString != null)
-				code = ResourceOperationCode.parse(opString);
-		}
-		
-		if(code==null){
-			if(commandName.startsWith("describe") || commandName.startsWith("list") || commandName.startsWith("status")
-					|| commandName.startsWith("show")){
-				code = ResourceOperationCode.LIST_DS;
-			} 
-		}
-		
-		//TODO : Have map according to each resources
-		//TODO : How to save information for retrieving command Option map or region and serverGroup
-		
-		Resource targetedResource = null;		
-		if(op!=null){
-			targetedResource = op.resource();
-		} else {			
-			targetedResource = Resource.DISTRIBUTED_SYSTEM;
-			//TODO : Add other resource and mbeans
-		}
-		
-		
-		LogService.getLogger().trace("#RegisterCommandSecurity : " + commandName + " code " + code + " op="+op);
-		
-		if(code!=null) {
-			commandToCodeMapping.put(commandName, code);
-		}
-		
-	}
+  private static void cache(String commandName, ResourceOperation op) {
+    ResourceOperationCode resourceOpCode = null;
+    
+    if (op != null) {
+      String opString = op.operation();
+      if (opString != null)
+        resourceOpCode = ResourceOperationCode.parse(opString);
+    }
+    
+    if(resourceOpCode==null){
+      if (commandName.startsWith(GETTER_DESCRIBE) || commandName.startsWith(GETTER_LIST)
+          || commandName.startsWith(GETTER_STATUS)) {
+        resourceOpCode = ResourceOperationCode.LIST_DS;
+      } 
+    }
+    
 
-	public Map<String, String> getCommandOptions() {
-		return commandOptions;
-	}
+    if(resourceOpCode!=null) {
+      commandToCodeMapping.put(commandName, resourceOpCode);
+    } else {
+      throw new GemFireConfigException(
+          "Error while configuring authorization for gfsh commands. No opCode defined for command " + commandName);
 
-	private static ResourceOperationCode findResourceCode(String commandName) {		
-		return commandToCodeMapping.get(commandName);
-	}
+    }
+    
+  }
 
+  public Map<String, String> getCommandOptions() {
+    return commandOptions;
+  }
 
-	@Override
-	public OperationCode getOperationCode() {		
-		return code;
-	}
+  private static ResourceOperationCode findResourceCode(String commandName) {   
+    return commandToCodeMapping.get(commandName);
+  }
 
-	@Override
-	public ResourceOperationCode getResourceOperationCode() {
-		return resourceCode;
-	}
-	
-	
-	public String toString(){
-	  String str;
-	  str = "CLIOperationContext(resourceCode=" + resourceCode + ") options=" + commandOptions+")";
-	  return str;
-	}
+
+  @Override
+  public OperationCode getOperationCode() {   
+    return code;
+  }
+
+  @Override
+  public ResourceOperationCode getResourceOperationCode() {
+    return resourceCode;
+  }
+  
+  
+  public String toString(){
+    String str;
+    str = "CLIOperationContext(resourceCode=" + resourceCode + ") options=" + commandOptions+")";
+    return str;
+  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JMXOperationContext.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JMXOperationContext.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JMXOperationContext.java
index 375cc27..49d30d6 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JMXOperationContext.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JMXOperationContext.java
@@ -9,153 +9,238 @@ import java.util.Map;
 import javax.management.ObjectName;
 
 import com.gemstone.gemfire.GemFireConfigException;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.management.AsyncEventQueueMXBean;
+import com.gemstone.gemfire.management.CacheServerMXBean;
+import com.gemstone.gemfire.management.DiskStoreMXBean;
+import com.gemstone.gemfire.management.DistributedLockServiceMXBean;
+import com.gemstone.gemfire.management.DistributedRegionMXBean;
 import com.gemstone.gemfire.management.DistributedSystemMXBean;
+import com.gemstone.gemfire.management.GatewayReceiverMXBean;
+import com.gemstone.gemfire.management.GatewaySenderMXBean;
+import com.gemstone.gemfire.management.LocatorMXBean;
+import com.gemstone.gemfire.management.LockServiceMXBean;
+import com.gemstone.gemfire.management.ManagerMXBean;
+import com.gemstone.gemfire.management.MemberMXBean;
+import com.gemstone.gemfire.management.RegionMXBean;
 import com.gemstone.gemfire.management.internal.MBeanJMXAdapter;
 import com.gemstone.gemfire.management.internal.cli.util.ClasspathScanLoadHelper;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.*;
 
-
+/**
+ * It describes current JMX MBean Method call and its parameters.
+ * OpCode returned by JMXOperationContext is retrieved from ResourceOperation annotation
+ * on the target methodName
+ * 
+ * @author tushark
+ * @since 9.0
+ *
+ */
 public class JMXOperationContext  extends ResourceOperationContext {
-	
-	private OperationCode code = OperationCode.RESOURCE;
-	private ResourceOperationCode resourceCode = null;
-	
-	private static Map<String,ResourceOperationCode> cacheDSResourceOps = null;
-	private static Map<String,ResourceOperationCode> cacheMemberResourceOps = null;
-	private static Map<String,ResourceOperationCode> cacheRegionResourceOps = null;
-	private static Map<String,ResourceOperationCode> cacheDiskStoreResourceOps = null;
-	
-	static {
-		//cache all resource annotations
-		readJMXAnnotations();		
-		
-	}	
+  
+  
+  private OperationCode code = OperationCode.RESOURCE;
+  private ResourceOperationCode resourceCode = null;
+  private ObjectName name;
+  private String methodName;
+  
+  private static Map<Class<?>,Map<String,ResourceOperationCode>> cachedResourceOpsMapping = new HashMap<Class<?>,Map<String,ResourceOperationCode>>();
+  private static Map<String,ResourceOperationCode> distributedSystemMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+  private static Map<String,ResourceOperationCode> diskStoreMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+  private static Map<String,ResourceOperationCode> cacheServerMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+  private static Map<String,ResourceOperationCode> gatewayReceiverMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+  private static Map<String,ResourceOperationCode> gatewaySenderMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+  private static Map<String,ResourceOperationCode> lockServiceMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+  private static Map<String,ResourceOperationCode> managerMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+  private static Map<String,ResourceOperationCode> memberMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+  private static Map<String,ResourceOperationCode> regionMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();  
+  private static Map<String,ResourceOperationCode> locatorMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();  
+  private static Map<String,ResourceOperationCode> distributedLockServiceMXBeanResourceOps = new HashMap<String,ResourceOperationCode>(); 
+  private static Map<String,ResourceOperationCode> distributedRegionMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();    
+  private static Map<String,ResourceOperationCode> asyncEventQueueMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+  private static Map<String,ResourceOperationCode> accessControlMXBeanResourceOps = new HashMap<String,ResourceOperationCode>();
+
+  
+  static {    
+    readJMXAnnotations();   
+  } 
 
-	private static void readJMXAnnotations() {
-		try {
-			Class[] klassList = ClasspathScanLoadHelper.getClasses("com.gemstone.gemfire.management");
-			for(Class klass : klassList) {
-				if(klass.getName().endsWith("MXBean")) {
-					Method[] methods = klass.getMethods();
-					for(Method method : methods) {
-						String name = method.getName();
-						//ResourceOperation op = method.getDeclaredAnnotations();(ResourceOperation.class);
-						boolean found=false;
-						Annotation ans[] = method.getDeclaredAnnotations();
-						for(Annotation an : ans){
-							if(an instanceof ResourceOperation) {
-								cache(klass,name,(ResourceOperation)an);
-								found=true;
-							}
-						}
-						if(!found)
-							cache(klass,name,null);
-					}
-					//TODO : Log all cached operations
-				}
-			}
-		} catch (ClassNotFoundException e) {			
-			throw new GemFireConfigException(
-					"Error while configuring authorization for jmx - ", e);
-		} catch (IOException e) {
-			throw new GemFireConfigException(
-					"Error while configuring authorization for jmx - ", e);
-		}
-		
-	}
-	
-	private static void cache(Class klass, String name, ResourceOperation op) {
-		ResourceOperationCode code = null;
-		
-		if (op != null) {
-			String opString = op.operation();
-			if (opString != null)
-				code = ResourceOperationCode.parse(opString);
-		}
-		
-		if(code==null){
-			if(name.startsWith("list") || name.startsWith("fetch") || name.startsWith("view")
-					|| name.startsWith("show")){
-				code = ResourceOperationCode.LIST_DS;
-			} else if (name.startsWith("get")){
-				code = ResourceOperationCode.READ_DS;
-			} else if (name.startsWith("is")){
-				code = ResourceOperationCode.READ_DS;
-			} else if (name.startsWith("set")){
-				code = ResourceOperationCode.SET_DS;
-			}
-		}
-		
-		/*
-		System.out.println("Klass " + klass + " mname : " + name);
-		if (code != null)
-			System.out.println("ResourceOperation code=" + code);
-		else
-			System.out.println("ResourceOperation is null");*/
-		
-		Resource targetedResource = null;
-		
-		if(op!=null){
-			targetedResource = op.resource();
-		} else {
-			if(klass.equals(DistributedSystemMXBean.class)) {
-				targetedResource = Resource.DISTRIBUTED_SYSTEM;
-			}
-			//TODO : Add other resource and mbeans
-		}
-		
-		/* Comment for timebeing to avoid falling for other methods
-		if(!isGetterSetter(name) && code==null){
-			throw new GemFireConfigException(
-					"Error while configuring authorization for jmx. No authorization defined for " 
-					+ klass.getCanonicalName() + " method " + name);
-		}*/
-		if(targetedResource!=null) {
-			switch (targetedResource) {
-			case DISTRIBUTED_SYSTEM:
-				if (code != null){
-					if(cacheDSResourceOps==null)
-						cacheDSResourceOps = new HashMap<String,ResourceOperationCode>();
-					cacheDSResourceOps.put(name, code);
-				}
-				break;
-			}
-		}			
-	}
+  private static void readJMXAnnotations() {
+    
+    cachedResourceOpsMapping.put(DistributedSystemMXBean.class, distributedSystemMXBeanResourceOps);
+    cachedResourceOpsMapping.put(DiskStoreMXBean.class, diskStoreMXBeanResourceOps);
+    cachedResourceOpsMapping.put(CacheServerMXBean.class, cacheServerMXBeanResourceOps);
+    cachedResourceOpsMapping.put(GatewayReceiverMXBean.class, gatewayReceiverMXBeanResourceOps);
+    cachedResourceOpsMapping.put(GatewaySenderMXBean.class, gatewaySenderMXBeanResourceOps);
+    cachedResourceOpsMapping.put(LockServiceMXBean.class, lockServiceMXBeanResourceOps);
+    cachedResourceOpsMapping.put(ManagerMXBean.class, managerMXBeanResourceOps);
+    cachedResourceOpsMapping.put(MemberMXBean.class, memberMXBeanResourceOps);
+    cachedResourceOpsMapping.put(RegionMXBean.class, regionMXBeanResourceOps);
+    cachedResourceOpsMapping.put(LocatorMXBean.class, locatorMXBeanResourceOps);
+    cachedResourceOpsMapping.put(DistributedLockServiceMXBean.class, distributedLockServiceMXBeanResourceOps);
+    cachedResourceOpsMapping.put(DistributedRegionMXBean.class, distributedRegionMXBeanResourceOps);
+    cachedResourceOpsMapping.put(AsyncEventQueueMXBean.class, asyncEventQueueMXBeanResourceOps);
+    cachedResourceOpsMapping.put(AccessControlMXBean.class, accessControlMXBeanResourceOps);
+    
+    try {
+      Class<?>[] klassList = ClasspathScanLoadHelper.getClasses(MANAGEMENT_PACKAGE);
+      for(Class<?> klass : klassList) {
+        if(klass.getName().endsWith("MXBean")) {
+          Method[] methods = klass.getMethods();
+          for(Method method : methods) {
+            String name = method.getName();
+            boolean found=false;
+            Annotation ans[] = method.getDeclaredAnnotations();
+            for(Annotation an : ans){
+              if(an instanceof ResourceOperation) {
+                cache(klass,name,(ResourceOperation)an);
+                found=true;
+              }
+            }
+            if(!found)
+              cache(klass,name,null);
+          }         
+        }
+      }
+    } catch (ClassNotFoundException e) {      
+      throw new GemFireConfigException(
+          "Error while configuring authorization for jmx - ", e);
+    } catch (IOException e) {
+      throw new GemFireConfigException(
+          "Error while configuring authorization for jmx - ", e);
+    }
+    
+  }
+  
+  private static void cache(Class<?> klass, String name, ResourceOperation op) {
+    ResourceOperationCode code = null;
+    
+    if (op != null) {
+      String opString = op.operation();
+      if (opString != null)
+        code = ResourceOperationCode.parse(opString);
+    }
+    
+    if(code==null && isGetterSetter(name)){        
+      code = ResourceOperationCode.LIST_DS;     
+    }
+    
+    
+    if (code == null && cachedResourceOpsMapping.keySet().contains(klass) && !isGetterSetter(name)) {      
+      throw new GemFireConfigException("Error while configuring authorization for jmx. No opCode defined for "
+          + klass.getCanonicalName() + " method " + name);
+    }
+    
+    final Map<String,ResourceOperationCode> resourceOpsMap = cachedResourceOpsMapping.get(klass);
+    if(resourceOpsMap==null) {
+      if (cachedResourceOpsMapping.keySet().contains(klass))
+        throw new GemFireConfigException("Unknown MBean " + klass.getCanonicalName());
+      else {
+        LogService.getLogger().warn("Unsecured mbean " + klass);
+      }
+    }
+    else {
+      resourceOpsMap.put(name, code);
+    }    
+  }
 
-	private static boolean isGetterSetter(String name) {
-		if(name.startsWith("is") || name.startsWith("get") ||  name.startsWith("set") ||  name.startsWith("fetch")
-			||  name.startsWith("list") ||  name.startsWith("view") ||  name.startsWith("show") ) 
-		return true;
-		else return false;
-	}
+  public static boolean isGetterSetter(String name) {
+    if(name.startsWith(GETTER_IS) || name.startsWith(GETTER_GET) ||  name.startsWith(GETTER_FETCH)
+      ||  name.startsWith(GETTER_LIST) ||  name.startsWith(GETTER_VIEW) ||  name.startsWith(GETTER_SHOW) ||  name.startsWith(GETTER_HAS)) 
+    return true;
+    else return false;
+  }
 
-	public JMXOperationContext(ObjectName name , String methodName){
-		code = OperationCode.RESOURCE;
-		if(name.equals(MBeanJMXAdapter.getDistributedSystemName())){
-			resourceCode = cacheDSResourceOps.get(methodName);
-		}
-	}
-	
+  public JMXOperationContext(ObjectName name , String methodName){
+    code = OperationCode.RESOURCE;    
+    Class<?> klass = getMbeanClass(name);
+    Map<String,ResourceOperationCode> resourceOpsMap = cachedResourceOpsMapping.get(klass);   
+    resourceCode = resourceOpsMap.get(methodName);
+    this.methodName = methodName;
+    this.name = name;
+    
+    //If getAttr is not found try for isAttr ie. boolean getter
+    if(resourceCode==null) {
+      if(this.methodName.startsWith(GET_PREFIX)) {
+        String methodNameBooleanGetter = GET_IS_PREFIX + this.methodName.substring(GET_PREFIX.length());
+        if(resourceOpsMap.containsKey(methodNameBooleanGetter)){
+          resourceCode = resourceOpsMap.get(methodNameBooleanGetter);
+          this.methodName = methodNameBooleanGetter;
+        }
+      }
+    }
+    
+    //If resourceCode is still null most likely its wrong method name so just allow it pass
+    if(resourceCode==null) {
+      resourceCode = ResourceOperationCode.LIST_DS;
+    }
+  }
+  
 
-	@Override
-	public OperationCode getOperationCode() {		
-		return code;
-	}
+  
 
-	@Override
-	public ResourceOperationCode getResourceOperationCode() {
-		return resourceCode;
-	}
+  private Class<?> getMbeanClass(ObjectName name) {
+    if (name.equals(MBeanJMXAdapter.getDistributedSystemName()))
+      return DistributedSystemMXBean.class;
+    else {
+      String service = name.getKeyProperty(MBEAN_KEY_SERVICE);
+      String mbeanType = name.getKeyProperty(MBEAN_KEY_TYPE);
 
-	public static Map<String, ResourceOperationCode> getCacheDSResourceOps() {
-		return cacheDSResourceOps;
-	}
+      if (MBEAN_TYPE_DISTRIBUTED.equals(mbeanType)) {
+        if (MBEAN_SERVICE_SYSTEM.equals(service)) {
+          return DistributedSystemMXBean.class;
+        } else if (MBEAN_SERVICE_REGION.equals(service)) {
+          return DistributedRegionMXBean.class;
+        } else if (MBEAN_SERVICE_LOCKSERVICE.equals(service)) {
+          return DistributedLockServiceMXBean.class;
+        } else {
+          throw new RuntimeException("Unknown mbean type " + name);
+        }
+      } else if (MBEAN_TYPE_MEMBER.equals(mbeanType)) {
+        if (service == null) {
+          return MemberMXBean.class;
+        } else {
+          if (MBEAN_SERVICE_MANAGER.equals(service)) {
+            return ManagerMXBean.class;
+          } else if (MBEAN_SERVICE_CACHESERVER.equals(service)) {
+            return CacheServerMXBean.class;
+          } else if (MBEAN_SERVICE_REGION.equals(service)) {
+            return RegionMXBean.class;
+          } else if (MBEAN_SERVICE_LOCKSERVICE.equals(service)) {
+            return LockServiceMXBean.class;
+          } else if (MBEAN_SERVICE_DISKSTORE.equals(service)) {
+            return DiskStoreMXBean.class;
+          } else if (MBEAN_SERVICE_GATEWAY_RECEIVER.equals(service)) {
+            return GatewayReceiverMXBean.class;
+          } else if (MBEAN_SERVICE_GATEWAY_SENDER.equals(service)) {
+            return GatewaySenderMXBean.class;
+          } else if (MBEAN_SERVICE_ASYNCEVENTQUEUE.equals(service)) {
+            return AsyncEventQueueMXBean.class;
+          } else if (MBEAN_SERVICE_LOCATOR.equals(service)) {
+            return LocatorMXBean.class;
+          } else {
+            throw new RuntimeException("Unknown mbean type " + name);
+          }
+        }
+      } else {
+        throw new RuntimeException("Unknown mbean type " + name);
+      }
+    }
+  }
 
-	public static void setCacheDSResourceOps(
-			Map<String, ResourceOperationCode> cacheDSResourceOps) {
-		JMXOperationContext.cacheDSResourceOps = cacheDSResourceOps;
-	}
-	
-	
+  @Override
+  public OperationCode getOperationCode() {   
+    return code;
+  }
+
+  @Override
+  public ResourceOperationCode getResourceOperationCode() {
+    return resourceCode;
+  }  
+  
+  public String toString(){
+    return "JMXOpCtx(on="+name+",method="+methodName+")";
+  }
 
 }
+

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JSONAuthorization.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JSONAuthorization.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JSONAuthorization.java
index d85ce65..5455818 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JSONAuthorization.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/JSONAuthorization.java
@@ -272,8 +272,8 @@ public class JSONAuthorization implements AccessControl, Authenticator {
 
   @Override
   public Principal authenticate(Properties props, DistributedMember arg1) throws AuthenticationFailedException {
-    String user = props.getProperty(ManagementInterceptor.USER_NAME);
-    String pwd = props.getProperty(ManagementInterceptor.PASSWORD);
+    String user = props.getProperty(ResourceConstants.USER_NAME);
+    String pwd = props.getProperty(ResourceConstants.PASSWORD);
     User userObj = acl.get(user);
     if(userObj==null)
       throw new AuthenticationFailedException("Wrong username/password");

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/MBeanServerWrapper.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/MBeanServerWrapper.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/MBeanServerWrapper.java
index 50942c1..0b91350 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/MBeanServerWrapper.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/MBeanServerWrapper.java
@@ -1,6 +1,7 @@
 package com.gemstone.gemfire.management.internal.security;
 
 import java.io.ObjectInputStream;
+import java.util.HashSet;
 import java.util.Set;
 
 import javax.management.Attribute;
@@ -25,7 +26,17 @@ import javax.management.QueryExp;
 import javax.management.ReflectionException;
 import javax.management.loading.ClassLoaderRepository;
 import javax.management.remote.MBeanServerForwarder;
-
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.*;
+
+/**
+ * This class intercepts all MBean requests for GemFire MBeans and passed it to 
+ * ManagementInterceptor for authorization
+ * 
+ * 
+ * @author tushark
+ * @since 9.0
+ *
+ */
 public class MBeanServerWrapper implements MBeanServerForwarder {
   
   private MBeanServer mbs;
@@ -35,52 +46,67 @@ public class MBeanServerWrapper implements MBeanServerForwarder {
     this.interceptor = interceptor;
   }
   
-  private void doAuthorization(ObjectName name, String methodName, Object[] methodParams){
-    interceptor.authorize(name,methodName, methodParams);
+  private ResourceOperationContext doAuthorization(ObjectName name, String methodName, Object[] methodParams){
+    return interceptor.authorize(name,methodName, methodParams);
+  }
+  
+  private void doAuthorizationPost(ObjectName name, String methodName, ResourceOperationContext context, Object result){
+    interceptor.postAuthorize(name,methodName,context,result);
   }
 
   @Override
   public ObjectInstance createMBean(String className, ObjectName name) throws ReflectionException,
       InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException {
-    doAuthorization(name, "createMBean", new Object[]{name});
-    return mbs.createMBean(className, name);
+    ResourceOperationContext ctx = doAuthorization(name, CREATE_MBEAN, new Object[]{name});
+    ObjectInstance result = mbs.createMBean(className, name);
+    doAuthorizationPost(name, CREATE_MBEAN, ctx, result);
+    return result;
   }
 
   @Override
   public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName)
       throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException,
       NotCompliantMBeanException, InstanceNotFoundException {
-    doAuthorization(name, "createMBean", new Object[]{name});
-    return mbs.createMBean(className, name, loaderName);
+    ResourceOperationContext ctx = doAuthorization(name, CREATE_MBEAN, new Object[]{name});
+    ObjectInstance result = mbs.createMBean(className, name, loaderName);
+    doAuthorizationPost(name, CREATE_MBEAN, ctx, result);
+    return result;
   }
 
   @Override
   public ObjectInstance createMBean(String className, ObjectName name, Object[] params, String[] signature)
       throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException,
       NotCompliantMBeanException {
-    doAuthorization(name, "createMBean", new Object[]{name, params});
-    return mbs.createMBean(className,name,params,signature);
+    ResourceOperationContext ctx = doAuthorization(name, CREATE_MBEAN, new Object[]{name, params});
+    ObjectInstance result = mbs.createMBean(className,name,params,signature);
+    doAuthorizationPost(name, CREATE_MBEAN, ctx, result);
+    return result;
   }
 
   @Override
   public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object[] params,
       String[] signature) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException,
       MBeanException, NotCompliantMBeanException, InstanceNotFoundException {
-    doAuthorization(name, "createMBean", new Object[]{name});
-    return mbs.createMBean(className, name, loaderName, params, signature);
+    ResourceOperationContext ctx = doAuthorization(name, CREATE_MBEAN, new Object[]{name});
+    ObjectInstance result = mbs.createMBean(className, name, loaderName, params, signature);
+    doAuthorizationPost(name, CREATE_MBEAN, ctx, result);
+    return result;
   }
 
   @Override
   public ObjectInstance registerMBean(Object object, ObjectName name) throws InstanceAlreadyExistsException,
       MBeanRegistrationException, NotCompliantMBeanException {
-    doAuthorization(name, "registerMBean", new Object[]{name});
-    return mbs.registerMBean(object, name);
+    ResourceOperationContext ctx = doAuthorization(name, REGISTER_MBEAN, new Object[]{name});
+    ObjectInstance result = mbs.registerMBean(object, name);
+    doAuthorizationPost(name, REGISTER_MBEAN, ctx, result);
+    return result;
   }
 
   @Override
   public void unregisterMBean(ObjectName name) throws InstanceNotFoundException, MBeanRegistrationException {
-    doAuthorization(name, "registerMBean", new Object[]{});
+    ResourceOperationContext ctx = doAuthorization(name, UNREGISTER_MBEAN, new Object[]{});
     mbs.unregisterMBean(name);
+    doAuthorizationPost(name, UNREGISTER_MBEAN, ctx, null);    
   }
 
   @Override
@@ -90,12 +116,32 @@ public class MBeanServerWrapper implements MBeanServerForwarder {
 
   @Override
   public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query) {
-    return mbs.queryMBeans(name, query);
+    return filterAccessControlMBeanInstance(mbs.queryMBeans(name, query));
+  }
+
+  private Set<ObjectInstance> filterAccessControlMBeanInstance(Set<ObjectInstance> queryMBeans) {
+    Set<ObjectInstance> set = new HashSet<ObjectInstance>();
+    for(ObjectInstance oi : queryMBeans) {
+      if(!oi.getObjectName().equals(interceptor.getAccessControlMBeanON())){
+        set.add(oi);
+      }
+    }
+    return set;
   }
 
   @Override
-  public Set<ObjectName> queryNames(ObjectName name, QueryExp query) {
-    return mbs.queryNames(name, query);
+  public Set<ObjectName> queryNames(ObjectName name, QueryExp query) {    
+    return filterAccessControlMBean(mbs.queryNames(name, query));
+  }
+
+  private Set<ObjectName> filterAccessControlMBean(Set<ObjectName> queryNames) {
+    Set<ObjectName> set = new HashSet<ObjectName>();
+    for(ObjectName oi : queryNames) {
+      if(!oi.equals(interceptor.getAccessControlMBeanON())){
+        set.add(oi);
+      }
+    }
+    return set;
   }
 
   @Override
@@ -111,36 +157,45 @@ public class MBeanServerWrapper implements MBeanServerForwarder {
   @Override
   public Object getAttribute(ObjectName name, String attribute) throws MBeanException, AttributeNotFoundException,
       InstanceNotFoundException, ReflectionException {
-    doAuthorization(name, "getAttribute",  new Object[]{attribute});
-    return mbs.getAttribute(name, attribute);
+    ResourceOperationContext ctx = doAuthorization(name, GET_ATTRIBUTE,  new Object[]{attribute});
+    Object result = mbs.getAttribute(name, attribute);
+    doAuthorizationPost(name, GET_ATTRIBUTE, ctx, result);
+    return result;
   }
 
   @Override
   public AttributeList getAttributes(ObjectName name, String[] attributes) throws InstanceNotFoundException,
       ReflectionException {
-    doAuthorization(name, "getAttributes", new Object[]{attributes});
-    return mbs.getAttributes(name, attributes);
+    ResourceOperationContext ctx = doAuthorization(name, GET_ATTRIBUTES, new Object[]{attributes});
+    AttributeList result = mbs.getAttributes(name, attributes);
+    doAuthorizationPost(name,GET_ATTRIBUTES, ctx, result);
+    return result;
   }
 
   @Override
   public void setAttribute(ObjectName name, Attribute attribute) throws InstanceNotFoundException,
       AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
-    doAuthorization(name, "setAttribute", new Object[]{attribute});
+    ResourceOperationContext ctx = doAuthorization(name, SET_ATTRIBUTE, new Object[]{attribute});
     mbs.setAttribute(name, attribute);
+    doAuthorizationPost(name, SET_ATTRIBUTE, ctx, null);
   }
 
   @Override
   public AttributeList setAttributes(ObjectName name, AttributeList attributes) throws InstanceNotFoundException,
       ReflectionException {
-    doAuthorization(name, "setAttributes", new Object[]{attributes});
-    return mbs.setAttributes(name, attributes);
+    ResourceOperationContext ctx = doAuthorization(name, SET_ATTRIBUTES, new Object[]{attributes});
+    AttributeList result = mbs.setAttributes(name, attributes);
+    doAuthorizationPost(name, SET_ATTRIBUTES, ctx, result);
+    return result;
   }
 
   @Override
   public Object invoke(ObjectName name, String operationName, Object[] params, String[] signature)
       throws InstanceNotFoundException, MBeanException, ReflectionException {
-    doAuthorization(name, operationName, new Object[]{params, signature});
-    return mbs.invoke(name, operationName, params, signature);
+    ResourceOperationContext ctx = doAuthorization(name, operationName, new Object[]{params, signature});
+    Object result = mbs.invoke(name, operationName, params, signature);
+    doAuthorizationPost(name, operationName, ctx, result);
+    return result;
   }
 
   @Override
@@ -224,6 +279,7 @@ public class MBeanServerWrapper implements MBeanServerForwarder {
     return mbs.instantiate(className, params, signature);
   }
 
+  @SuppressWarnings("deprecation")
   @Override
   public ObjectInputStream deserialize(ObjectName name, byte[] data) throws InstanceNotFoundException,
       OperationsException {
@@ -268,3 +324,4 @@ public class MBeanServerWrapper implements MBeanServerForwarder {
   }
 
 }
+

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ManagementInterceptor.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ManagementInterceptor.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ManagementInterceptor.java
index 1851977..9158ddd 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ManagementInterceptor.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ManagementInterceptor.java
@@ -1,13 +1,32 @@
 package com.gemstone.gemfire.management.internal.security;
 
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.ACCESS_DENIED_MESSAGE;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.GET_ATTRIBUTE;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.GET_ATTRIBUTES;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.GET_PREFIX;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.PASSWORD;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.PROCESS_COMMAND;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.SET_ATTRIBUTE;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.SET_ATTRIBUTES;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.SET_PREFIX;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.USER_NAME;
+import static com.gemstone.gemfire.management.internal.security.ResourceConstants.WRONGE_CREDENTIALS_MESSAGE;
+
 import java.lang.management.ManagementFactory;
+import java.lang.reflect.Method;
 import java.security.AccessControlContext;
 import java.security.AccessController;
 import java.security.Principal;
 import java.util.Collections;
+import java.util.List;
+import java.util.Map.Entry;
 import java.util.Properties;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
 
+import javax.management.Attribute;
+import javax.management.AttributeList;
 import javax.management.InstanceAlreadyExistsException;
 import javax.management.MBeanRegistrationException;
 import javax.management.MBeanServer;
@@ -22,234 +41,324 @@ import javax.security.auth.Subject;
 import org.apache.logging.log4j.Logger;
 
 import com.gemstone.gemfire.GemFireConfigException;
-import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.distributed.DistributedSystem;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.ClassLoadUtil;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.lang.StringUtils;
+import com.gemstone.gemfire.internal.logging.InternalLogWriter;
+import com.gemstone.gemfire.management.internal.ManagementConstants;
 import com.gemstone.gemfire.security.AccessControl;
+import com.gemstone.gemfire.security.AuthenticationFailedException;
 import com.gemstone.gemfire.security.Authenticator;
 
-@SuppressWarnings("rawtypes")
+/**
+ * 
+ * ManagementInterceptor is central go-to place for all M&M Clients Authentication and Authorization
+ * requests
+ * 
+ * @author tushark
+ * @since 9.0
+ * 
+ */
 public class ManagementInterceptor implements JMXAuthenticator {
 
-	public static final String USER_NAME = "security-username";
-	public static final String PASSWORD = "security-password";
-	public static final String OBJECT_NAME_ACCESSCONTROL = "GemFire:service=AccessControl,type=Distributed";
-	private MBeanServerWrapper mBeanServerForwarder;
-	private Logger logger;  
+  private MBeanServerWrapper mBeanServerForwarder;
+  private Logger logger;
+  private ObjectName accessControlMBeanON;
+  private Cache cache;
+  private String authzFactoryName;
+  private String postAuthzFactoryName;
+  private String authenticatorFactoryName;
+  private ConcurrentMap<Principal, AccessControl> cachedAuthZCallback;
+  private ConcurrentMap<Principal, AccessControl> cachedPostAuthZCallback;
 
-	public ManagementInterceptor(Logger logger) {
-		this.logger = logger;		
-		this.mBeanServerForwarder = new MBeanServerWrapper(this);
-		registerAccessContorlMbean();
-		LogService.getLogger().info("Starting management interceptor");
-	}
+  public ManagementInterceptor(Cache gemFireCacheImpl, Logger logger) {
+    this.cache = gemFireCacheImpl;
+    this.logger = logger;
+    this.mBeanServerForwarder = new MBeanServerWrapper(this);
+    DistributedSystem system = cache.getDistributedSystem();
+    Properties sysProps = system.getProperties();
+    this.authzFactoryName = sysProps.getProperty(DistributionConfig.SECURITY_CLIENT_ACCESSOR_NAME);
+    this.postAuthzFactoryName = sysProps.getProperty(DistributionConfig.SECURITY_CLIENT_ACCESSOR_PP_NAME);
+    this.authenticatorFactoryName = sysProps.getProperty(DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME);
+    this.cachedAuthZCallback = new ConcurrentHashMap<Principal, AccessControl>();
+    this.cachedPostAuthZCallback = new ConcurrentHashMap<Principal, AccessControl>();
+    registerAccessContorlMbean();
+    logger.info("Started Management interceptor on JMX connector");
+  }
 
-	private void registerAccessContorlMbean() {    
+  /**
+   * This method registers an AccessControlMBean which allows any remote JMX Client (for example Pulse) to check for
+   * access allowed for given Operation Code.
+   */
+  private void registerAccessContorlMbean() {
     try {
-      com.gemstone.gemfire.management.internal.security.AccessControl acc = new com.gemstone.gemfire.management.internal.security.AccessControl(this);
-      ObjectName name = new ObjectName(OBJECT_NAME_ACCESSCONTROL);
+      com.gemstone.gemfire.management.internal.security.AccessControl acc = new com.gemstone.gemfire.management.internal.security.AccessControl(
+          this);
+      accessControlMBeanON = new ObjectName(ResourceConstants.OBJECT_NAME_ACCESSCONTROL);
       MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
-      Set<ObjectName> names = platformMBeanServer.queryNames(name, null);
-      if(names.isEmpty()) {
+      Set<ObjectName> names = platformMBeanServer.queryNames(accessControlMBeanON, null);
+      if (names.isEmpty()) {
         try {
-          platformMBeanServer.registerMBean(acc, name);
-          logger.info("Registered AccessContorlMBean on " + name);
+          platformMBeanServer.registerMBean(acc, accessControlMBeanON);
+          logger.info("Registered AccessContorlMBean on " + accessControlMBeanON);
         } catch (InstanceAlreadyExistsException e) {
-          throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource",e);
+          throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource", e);
         } catch (MBeanRegistrationException e) {
-          throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource",e);
+          throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource", e);
         } catch (NotCompliantMBeanException e) {
-          throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource",e);
+          throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource", e);
         }
       }
-    } catch (MalformedObjectNameException e) {      
-      e.printStackTrace();
+    } catch (MalformedObjectNameException e) {
+      throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource", e);
     }
   }
 
+  /**
+   * Delegates authentication to GemFire Authenticator
+   * 
+   * @throws SecurityException
+   *           if authentication fails
+   */
   @Override
-	public Subject authenticate(Object credentials) {
-		String username = null, password = null;
-		if (!(credentials instanceof String[])) {
-			// Special case for null so we get a more informative message
-			if (credentials == null) {
-				// throw new SecurityException("Credentials required");
-				username = "empty";
-				password = "emptypwd";
-			}
-			// throw new SecurityException("Credentials should be String[]");
-			username = "empty";
-			password = "emptypwd";
-			
-			//TODO ***** Remove empty stuff
-			
-		} else {
-			final String[] aCredentials = (String[]) credentials;
-			username = (String) aCredentials[0];
-			password = (String) aCredentials[1];
-		}
-
-		Properties pr = new Properties();
-		pr.put(USER_NAME, username);
-		pr.put(PASSWORD, password);
-		getAuthenticator(pr).authenticate(pr, null);
-		return new Subject(true, Collections.singleton(new JMXPrincipal(username)), Collections.EMPTY_SET,
-			    Collections.EMPTY_SET);
-	}
-
-	@SuppressWarnings("unchecked")
-	public void authorize(ObjectName name, final String methodName, Object[] params) {
-	  
+  public Subject authenticate(Object credentials) {    
+    String username = null, password = null;
+    Properties pr = new Properties();
+    if (credentials instanceof String[]) {
+      final String[] aCredentials = (String[]) credentials;
+      username = (String) aCredentials[0];
+      password = (String) aCredentials[1];
+      pr.put(USER_NAME, username);
+      pr.put(PASSWORD, password);
+    } else if (credentials instanceof Properties) {
+      pr = (Properties) credentials;
+    } else {
+      throw new SecurityException(WRONGE_CREDENTIALS_MESSAGE);
+    }
+    
     try {
-      ObjectName accessControlMBean = new ObjectName(OBJECT_NAME_ACCESSCONTROL);
-      if (name.equals(accessControlMBean)) {
-        logger.info("Granting access to accessContorlMXBean.. name="+name);
-        return;
+      Principal principal = getAuthenticator(cache.getDistributedSystem().getSecurityProperties()).authenticate(pr,
+          cache.getDistributedSystem().getDistributedMember());
+      return new Subject(true, Collections.singleton(new JMXPrincipal(principal.getName())), Collections.EMPTY_SET,
+          Collections.EMPTY_SET);
+    } catch (AuthenticationFailedException e) {
+      //wrap inside Security exception. AuthenticationFailedException is gemfire class
+      //which generic JMX client can't serialize
+      throw new SecurityException("Authentication Failed " + e.getMessage());
+    }
+    
+  }
+
+  /**
+   * Builds ResourceOperationContext for the given JMX MBean Request for delegates Authorization to
+   * gemfire AccessControl plugin with context as parameter
+   * 
+   * 
+   * @param name
+   * @param methodName
+   * @param params
+   * 
+   * @throws SecurityException
+   *           if access is not granted
+   */
+  public ResourceOperationContext authorize(ObjectName name, final String methodName, Object[] params) {
+    
+    if (StringUtils.isBlank(authzFactoryName)){
+      return com.gemstone.gemfire.management.internal.security.AccessControlContext.ACCESS_GRANTED_CONTEXT;
+    }
+
+    if (name.equals(accessControlMBeanON)) {
+      return com.gemstone.gemfire.management.internal.security.AccessControlContext.ACCESS_GRANTED_CONTEXT;
+    }
+
+    if (!ManagementConstants.OBJECTNAME__DEFAULTDOMAIN.equals(name.getDomain()))
+      return com.gemstone.gemfire.management.internal.security.AccessControlContext.ACCESS_GRANTED_CONTEXT;
+
+    AccessControlContext acc = AccessController.getContext();
+    Subject subject = Subject.getSubject(acc);
+    
+    // Allow operations performed locally on behalf of the connector server itself
+    if (subject == null) {
+      return com.gemstone.gemfire.management.internal.security.AccessControlContext.ACCESS_GRANTED_CONTEXT;
+    }
+
+    if (methodName.equals(ResourceConstants.CREATE_MBEAN) || methodName.equals(ResourceConstants.UNREGISTER_MBEAN)) {
+      throw new SecurityException(ACCESS_DENIED_MESSAGE);
+    }
+
+    Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class);
+
+    if (principals == null || principals.isEmpty()) {
+      throw new SecurityException(ACCESS_DENIED_MESSAGE);
+    }
+
+    Principal principal = principals.iterator().next();
+
+    
+    if (logger.isDebugEnabled()) {
+      logger.debug("Name=" + name + " methodName=" + methodName + " principal=" + principal.getName());
+    }
+
+    AccessControl accessControl = getAccessControl(principal, false);
+    String method = methodName;
+    if (methodName.equals(GET_ATTRIBUTE)) {
+      method = GET_PREFIX + (String) params[0];
+    } else if(methodName.equals(GET_ATTRIBUTES)) {
+      //Pass to first attribute getter
+      String[] attrs = (String[]) params[0];
+      method = GET_PREFIX + attrs[0];
+    } else if(methodName.equals(SET_ATTRIBUTE)) {
+      Attribute attribute = (Attribute) params[0];
+      method = SET_PREFIX + attribute.getName();
+    }    
+    
+    if (methodName.equals(SET_ATTRIBUTES)) {
+      AttributeList attrList = (AttributeList) params[0];
+      List<Attribute> list = attrList.asList();
+      ResourceOperationContext setterContext = null;
+      SetAttributesOperationContext resourceContext = new SetAttributesOperationContext();      
+      for(int i=0;i<list.size();i++) {
+        Attribute attribute = list.get(i);
+        String setter = SET_PREFIX + attribute.getName();
+        setterContext = buildContext(name,setter,null);
+        boolean authorized = accessControl.authorizeOperation(null, setterContext);
+        if (logger.isDebugEnabled()) {
+          logger.debug("Name=" + name + " methodName=" + methodName + " result=" + authorized + " principal="
+              + principal.getName());
+        }
+        if (!authorized)
+          throw new SecurityException(ACCESS_DENIED_MESSAGE);
+        else
+          resourceContext.addAttribute(attribute.getName(), setterContext);
+      }
+      return resourceContext;
+    } else {
+      ResourceOperationContext resourceContext = buildContext(name, method, params);
+      boolean authorized = accessControl.authorizeOperation(null, resourceContext);
+      if (logger.isDebugEnabled()) {
+        logger.debug("Name=" + name + " methodName=" + methodName + " result=" + authorized + " principal="
+            + principal.getName());
       }
-    } catch (MalformedObjectNameException e) {
-      // TODO Auto-generated catch block
-      // e.printStackTrace();
-    }
-	  
-	  
-	  //Only apply for gemfire domain
-	  String domain = name.getDomain();
-	  if(!"GemFire".equals(domain))
-	    return;
-	  
-		// Retrieve Subject from current AccessControlContext
-		AccessControlContext acc = AccessController.getContext();		
-		Subject subject = Subject.getSubject(acc);
-		// Allow operations performed locally on behalf of the connector server
-		// itself
-		if (subject == null) {
-			return;
-		}
-
-		// Restrict access to "createMBean" and "unregisterMBean" to any user
-		if (methodName.equals("createMBean")
-				|| methodName.equals("unregisterMBean")) {
-			throw new SecurityException("Access denied");
-		}
-
-		// Retrieve JMXPrincipal from Subject
-		Set<JMXPrincipal> principals = subject
-				.getPrincipals(JMXPrincipal.class);
-		Set<Object> pubCredentials = subject.getPublicCredentials();
-		
-		/*System.out.println("JMXPrincipal " + principals);
-		System.out.println("Principals " + subject.getPrincipals());
-		System.out.println("PubCredentials " + subject.getPublicCredentials());*/
-		//add condition -> check if accessor is configured
-		if (principals == null || principals.isEmpty()
-				/*|| pubCredentials.size() < 1 */) {
-			throw new SecurityException("Access denied");
-		}		
-	
-		Principal principal = principals.iterator().next();
-		
-		//Give read access globally : TODO : Need to change this to map to proper getter
-		LogService.getLogger().info("Name=" + name + " methodName=" +  methodName + " principal="+ principal.getName());
-		if("getAttribute".equals(methodName) || "getAttributes".equals(methodName))
-			return;	
-		
-		//TODO : if method=getAttributes params is directly availalbe
-		//TODO : if method is operation then params is array array[0] = actual params, array[1]= signature
-		
-		ResourceOperationContext resourceContext = buildContext(name,methodName, params);		
-		boolean authorized = getAccessControl(principal).authorizeOperation(null, resourceContext);
-		LogService.getLogger().info("Name=" + name + " methodName=" +  methodName 
-		    + " result="+authorized + " principal="+ principal.getName());
-		if(!authorized)
-			throw new SecurityException("Access denied");
-	}
-
-	public MBeanServerForwarder getMBeanServerForwarder() {
-		return mBeanServerForwarder;
-	}
-
-	private static Class accessControlKlass = null;
-	
-	public AccessControl getAccessControl(Principal principal) {
-		if(accessControlKlass==null) {
-			String authorizeKlass = System.getProperty(ResourceConstants.RESORUCE_AUTH_ACCESSOR);
-			try {
-				accessControlKlass = Class.forName(authorizeKlass);
-			} catch (ClassNotFoundException e) {
-			  logger.error(e);
-				throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource",e);
-			}
-		}
-		
-		try {
-			AccessControl accessControl = (AccessControl) accessControlKlass.newInstance();
-			accessControl.init(principal, null, null); //TODO pass proper params
-			LogService.getLogger().info("Returning resource accessControl");
-			return accessControl;
-		} catch (InstantiationException e) {
-		  logger.error(e);
-			throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource",e);
-		} catch (IllegalAccessException e) {
-		  logger.error(e);
-			throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource",e);
-		}
-	}
-
-	private static Class authenticatorClass = null;
-	private Authenticator getAuthenticator(Properties pr) {
-		if(authenticatorClass==null) {
-			String authenticatorKlass = System.getProperty(ResourceConstants.RESORUCE_AUTHENTICATOR);
-			try {
-				authenticatorClass = Class.forName(authenticatorKlass);
-			} catch (ClassNotFoundException e) {	
-			  logger.error(e);
-				throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource",e);
-			}
-		}
-		
-		try {
-			Authenticator authenticator = (Authenticator) authenticatorClass.newInstance();
-			authenticator.init(pr, null, null); //TODO pass proper params
-			LogService.getLogger().info("Returning resource authenticator " + authenticator);
-			return authenticator;
-		} catch (InstantiationException e) {
-		  logger.error(e);
-			throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource",e);
-		} catch (IllegalAccessException e) {
-		  logger.error(e);
-			throw new GemFireConfigException("Error while configuring accesscontrol for jmx resource",e);
-		}
-	}
 
-  private ResourceOperationContext buildContext(ObjectName name, String methodName, Object[] params) {
-    if (params != null) {
-      LogService.getLogger().info("Params length=" + params.length);
-      for (int i = 0; i < params.length; i++) {
-        LogService.getLogger().info("Params[" + i + "] is " + arrayString(params[i]));
+      if (!authorized)
+        throw new SecurityException(ACCESS_DENIED_MESSAGE);
+      return resourceContext;
+    }
+  }
+
+  public MBeanServerForwarder getMBeanServerForwarder() {
+    return mBeanServerForwarder;
+  }
+
+  public AccessControl getAccessControl(Principal principal, boolean isPost) {
+    if (!isPost) {
+      if (cachedAuthZCallback.containsKey(principal)) {
+        return cachedAuthZCallback.get(principal);
+      } else if (!StringUtils.isBlank(authzFactoryName)) {
+        try {
+          Method authzMethod = ClassLoadUtil.methodFromName(authzFactoryName);
+          AccessControl authzCallback = (AccessControl) authzMethod.invoke(null, (Object[]) null);
+          authzCallback.init(principal, null, cache);          
+          cachedAuthZCallback.put(principal, authzCallback);
+          return authzCallback;
+        } catch (Exception ex) {
+          throw new AuthenticationFailedException(
+              LocalizedStrings.HandShake_FAILED_TO_ACQUIRE_AUTHENTICATOR_OBJECT.toLocalizedString(), ex);
+        }
       }
+    } else {
+      if (cachedPostAuthZCallback.containsKey(principal)) {
+        return cachedPostAuthZCallback.get(principal);
+      } else if (!StringUtils.isBlank(postAuthzFactoryName)) {
+        try {
+          Method authzMethod = ClassLoadUtil.methodFromName(postAuthzFactoryName);
+          AccessControl postAuthzCallback = (AccessControl) authzMethod.invoke(null, (Object[]) null);
+          postAuthzCallback.init(principal, null, cache);
+          cachedPostAuthZCallback.put(principal, postAuthzCallback);
+          return postAuthzCallback;
+        } catch (Exception ex) {
+          throw new AuthenticationFailedException(
+              LocalizedStrings.HandShake_FAILED_TO_ACQUIRE_AUTHENTICATOR_OBJECT.toLocalizedString(), ex);
+        }
+      }
+    }
+    return null;
+  }
+
+  private Authenticator getAuthenticator(Properties gfSecurityProperties) throws AuthenticationFailedException {
+    Authenticator auth;
+    try {
+      Method instanceGetter = ClassLoadUtil.methodFromName(this.authenticatorFactoryName);
+      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(gfSecurityProperties,(InternalLogWriter) this.cache.getLogger(), (InternalLogWriter) this.cache.getSecurityLogger());
+    return auth;
+  }
 
+  private ResourceOperationContext buildContext(ObjectName name, String methodName, Object[] params) {
     String service = name.getKeyProperty("service");
-    // only member mbean does not have service KeyProperty
-    if (service == null && "processCommand".equals(methodName)) {
+    if (service == null && PROCESS_COMMAND.equals(methodName)) {
       Object[] array = (Object[]) params[0];
       String command = (String) array[0];
-      CLIOperationContext context = new CLIOperationContext(command);      
-      LogService.getLogger().info("Returning CLIContext for " + methodName);
+      CLIOperationContext context = new CLIOperationContext(command);
       return context;
-    } else {
+    } else {      
       ResourceOperationContext context = new JMXOperationContext(name, methodName);
-      LogService.getLogger().info("Returning JMXOperationContext for " + methodName);
       return context;
     }
   }
 
-  private String arrayString(Object object) {
-    StringBuilder sb = new StringBuilder();
-    if (object instanceof Object[]) {
-      Object[] array = (Object[]) object;
-      for (Object a : array)
-        sb.append(a).append(" ");
+  public ObjectName getAccessControlMBeanON() {
+    return accessControlMBeanON;
+  }
+
+  public void postAuthorize(ObjectName name, final String methodName, ResourceOperationContext context, Object result) {
+    
+    if (StringUtils.isBlank(postAuthzFactoryName)){
+      return ;
+    }
+    
+    context.setPostOperationResult(result);
+
+    if (context.equals(com.gemstone.gemfire.management.internal.security.AccessControlContext.ACCESS_GRANTED_CONTEXT))
+      return;
+
+    AccessControlContext acc = AccessController.getContext();
+    Subject subject = Subject.getSubject(acc);
+    Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class);
+    if (principals == null || principals.isEmpty()) {
+      throw new SecurityException(ACCESS_DENIED_MESSAGE);
+    }
+    Principal principal = principals.iterator().next();
+    AccessControl accessControl = getAccessControl(principal, true);
+    if (context instanceof SetAttributesOperationContext) {
+      SetAttributesOperationContext setterContext = (SetAttributesOperationContext) context;
+      for (Entry<String, ResourceOperationContext> e : setterContext.getAttributesContextMap().entrySet()) {
+        //TODO : Retrieve proper values from AttributeList and set to its jmxContext
+        e.getValue().setPostOperationResult(result);
+        boolean authorized = accessControl.authorizeOperation(null, e.getValue());
+        if (!authorized)
+          throw new SecurityException(ACCESS_DENIED_MESSAGE);
+      }
+    } else {
+      boolean authorized = accessControl.authorizeOperation(null, context);
+      if (logger.isDebugEnabled()) {
+        logger.debug("postAuthorize: Name=" + name + " methodName=" + methodName + " result=" + authorized
+            + " principal=" + principal.getName());
+      }
+      if (!authorized)
+        throw new SecurityException(ACCESS_DENIED_MESSAGE);
     }
-    return sb.toString();
   }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/Resource.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/Resource.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/Resource.java
index 4dc27e1..68b0468 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/Resource.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/Resource.java
@@ -1,10 +1,17 @@
 package com.gemstone.gemfire.management.internal.security;
 
+/**
+ * 
+ * @author tushark
+ *
+ * @since 9.0
+ */
 public enum Resource {
   DISTRIBUTED_SYSTEM,
   MEMBER,
   REGION,
   DISKSTORE,
   GATEWAY_SENDER,
-  GATEWAT_LISTENER,  
+  GATEWAY_RECEIVER,  
 }
+

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceConstants.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceConstants.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceConstants.java
index 3f4d7cb..e26bc64 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceConstants.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceConstants.java
@@ -1,37 +1,32 @@
 package com.gemstone.gemfire.management.internal.security;
 
+/**
+ * 
+ * @author tushark
+ *
+ * @since 9.0
+ */
 public class ResourceConstants {
-	
-	//public static final String LIST_DS = "LIST_DS";
-	public static final String READ_DS = "READ_DS";
-	public static final String SET_DS = "SET_DS";
-	public static final String CHANGE_ALERT_LEVEL_DS = "CHANGE_ALERT_LEVEL_DS";
-	public static final String BACKUP_DS = "BACKUP_DS";
-	public static final String REMOVE_DISKSTORE_DS = "REMOVE_DISKSTORE_DS";
-	public static final String SHUTDOWN_DS = "SHUTDOWN_DS";
-	public static final String QUERYDATA_DS = "QUERYDATA_DS";
-	public static final String ADMIN_DS = "ADMIN_DS";
-	
-	/*
-	public static final String REBALANCE = "REBALANCE";
-	public static final String PUT = "PUT";
-	public static final String EXPORT_DATA = "EXPORT_DATA";
-	public static final String IMPORT_DATA = "IMPORT_DATA";
-	public static final String LOCATE_ENTRY = "LOCATE_ENTRY";*/
-	
-	public static final String PULSE_DASHBOARD = "PULSE_DASHBOARD";
-  public static final String PULSE_DATABROWSER = "PULSE_DATABROWSER";
-  public static final String PULSE_ADMIN_V1 = "PULSE_ADMIN_V1";
-  public static final String PULSE_WEBGFSH = "PULSE_WEBGFSH";  
-	
-	public static final String DEFAULT_LABEL="";
-	
-	public static final String RESORUCE_SEC_DESCRIPTOR = "resource.secDescriptor";
-	public static final String RESORUCE_AUTH_ACCESSOR = "resource-auth-accessor";
-	public static final String RESORUCE_AUTHENTICATOR = "resource-authenticator";
-  public static final String RESORUCE_DEFAULT_SEC_DESCRIPTOR = "resourceSecDesc.json";
   
-  //All ResourceOperation Codes
+  public static final String DEFAULT_LABEL="";
+  
+  public static final String RESORUCE_SEC_DESCRIPTOR = "resource.secDescriptor";
+  public static final String RESORUCE_AUTH_ACCESSOR = "resource-auth-accessor";
+  public static final String RESORUCE_AUTHENTICATOR = "resource-authenticator";
+  public static final String RESORUCE_DEFAULT_SEC_DESCRIPTOR = "resourceSecDesc.json";
+  public static final String CREATE_MBEAN = "createMBean";
+  public static final String UNREGISTER_MBEAN = "unregisterMBean";
+  public static final String SET_PREFIX = "set";
+  public static final String SET_ATTRIBUTE = "setAttribute";
+  public static final String SET_ATTRIBUTES= "setAttributes";
+  public static final String GET_ATTRIBUTES= "getAttributes";
+  public static final String GET_ATTRIBUTE = "getAttribute";
+  public static final String GET_PREFIX = "get";
+  public static final String GET_IS_PREFIX = "is";
+  public static final String REGISTER_MBEAN = "registerMBean";
+  public static final String PROCESS_COMMAND ="processCommand";
+  public static final String ACCESS_DENIED_MESSAGE = "Access Denied";
+  public static final String WRONGE_CREDENTIALS_MESSAGE = "Wrong Credentials";
   
   public static final String ALTER_REGION = "ALTER_REGION";
   public static final String ALTER_RUNTIME = "ALTER_RUNTIME";
@@ -51,6 +46,7 @@ public class ResourceConstants {
   public static final String DESTROY_DISKSTORE = "DESTROY_DISKSTORE";
   public static final String DESTROY_FUNCTION = "DESTROY_FUNCTION";
   public static final String DESTROY_INDEX = "DESTROY_INDEX";
+  
   public static final String DESTROY_REGION = "DESTROY_REGION";
   public static final String EXECUTE_FUNCTION = "EXECUTE_FUNCTION";
   public static final String EXPORT_CONFIG = "EXPORT_CONFIG";
@@ -86,6 +82,7 @@ public class ResourceConstants {
   public static final String BACKUP_MEMBERS = "BACKUP_MEMBERS";
   public static final String ROLL_DISKSTORE = "ROLL_DISKSTORE";
   public static final String FORCE_COMPACTION = "FORCE_COMPACTION";
+  public static final String FORCE_ROLL = "FORCE_ROLL";
   public static final String FLUSH_DISKSTORE = "FLUSH_DISKSTORE";
   public static final String START_GW_RECEIVER = "START_GW_RECEIVER";
   public static final String START_GW_SENDER = "START_GW_SENDER";
@@ -93,7 +90,55 @@ public class ResourceConstants {
   public static final String START_MANAGER = "START_MANAGER";
   public static final String STOP_MANAGER = "STOP_MANAGER";
   public static final String CREATE_MANAGER = "CREATE_MANAGER";
+  public static final String STOP_CONTINUOUS_QUERY = "STOP_CONTINUOUS_QUERY";
+  public static final String SET_DISK_USAGE = "SET_DISK_USAGE";
+  
+  public static final String CREATE_HDFS_STORE = "CREATE_HDFS_STORE";
+  public static final String ALTER_HDFS_STORE = "ALTER_HDFS_STORE";
+  public static final String DESTROY_HDFS_STORE = "DESTROY_HDFS_STORE";
+  
+  public static final String PULSE_DASHBOARD = "PULSE_DASHBOARD";
+  public static final String PULSE_DATABROWSER = "PULSE_DATABROWSER";
+  public static final String PULSE_ADMIN_V1 = "PULSE_ADMIN_V1";
+  public static final String PULSE_WEBGFSH = "PULSE_WEBGFSH";
+
+  public static final String DATA_READ = "DATA_READ";
+  public static final String DATA_WRITE = "DATA_WRITE";
+  public static final String MONITOR = "MONITOR";
+  public static final String ADMIN = "ADMIN";
+  
+  public static final String OBJECT_NAME_ACCESSCONTROL = "GemFire:service=AccessControl,type=Distributed";
+  public static final String USER_NAME = "security-username";
+  public static final String PASSWORD = "security-password";
 
+  public static final String MBEAN_TYPE_DISTRIBUTED = "Distributed";
+  public static final String MBEAN_TYPE_MEMBER = "Member";
+  
+  public static final String MBEAN_SERVICE_MANAGER = "Manager";
+  public static final String MBEAN_SERVICE_CACHESERVER="CacheServer";
+  public static final String MBEAN_SERVICE_REGION = "Region";
+  public static final String MBEAN_SERVICE_LOCKSERVICE = "LockService";
+  public static final String MBEAN_SERVICE_DISKSTORE = "DiskStore";
+  public static final String MBEAN_SERVICE_GATEWAY_RECEIVER = "GatewayReceiver";
+  public static final String MBEAN_SERVICE_GATEWAY_SENDER = "GatewaySender";
+  public static final String MBEAN_SERVICE_ASYNCEVENTQUEUE = "AsyncEventQueue";
+  public static final String MBEAN_SERVICE_LOCATOR = "Locator";
+  public static final String MBEAN_SERVICE_SYSTEM = "System";
+  
+  public static final String MBEAN_KEY_SERVICE ="service";
+  public static final String MBEAN_KEY_TYPE ="type";
+  
+  public static final String GETTER_IS= "is";
+  public static final String GETTER_GET = "get";
+  public static final String GETTER_FETCH = "fetch";
+  public static final String GETTER_SHOW = "show";
+  public static final String GETTER_HAS = "has";
+  public static final String GETTER_VIEW = "view";
+  public static final String GETTER_LIST = "list";
+  public static final String GETTER_DESCRIBE = "describe";
+  public static final String GETTER_STATUS = "status";
+  
+  public static final String MANAGEMENT_PACKAGE = "com.gemstone.gemfire.management";
   
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/d511979e/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperation.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperation.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperation.java
index f149479..48cbd94 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperation.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/security/ResourceOperation.java
@@ -6,6 +6,12 @@ import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 
+/**
+ * Annotation describing Security Level required to perform any resource operation
+ * @author tushark
+ *
+ * @since 9.0
+ */
 @Target(ElementType.METHOD)
 @Retention(RetentionPolicy.RUNTIME)
 @Inherited