Example: Apply permissions to a service

This example demonstrates how you can apply permissions to a service programmatically. Permissions are a set of rules about which roles can or cannot access a service.

In this example, the service is first made private by denying access to the esriEveryone role, a fictitious role for the purpose of this example that includes all users of the site. Then a second rule is added to grant a user-supplied role permissions to access the geometry service. An extra function is included in the code to show how you could make the service public by granting access to the esriEveryone role again.

The script attempts to log in and acquire the token securely through HTTPS (encrypted connection). If HTTPS has not been configured on your ArcGIS Server, the default behavior is for the script to attempt an insecure login (no encryption). If you wish to require a secure login, then use the --secure option with the script.

The script is written in Python but does not require any Esri software to be installed. To run the script, do the following:

[Windows]

  1. Save the content to a file setPermissions.py.

  2. Start a command prompt.

  3. Run the setPermission.py. Here is an example:

    setPermissions.py --user admin --password secret --role "GIS Department"

[Linux]

  1. Save the content to a file setPermissions.py.

  2. Make the file executable (chmod u+x).

  3. If Python does not exist in /usr/bin, edit the first line to point to your installation of Python (this step is usually not needed).

  4. Run setPermissions.py. Here is an example:

    ./setPermissions.py --user admin --password secret --role "GIS Department"

#!/usr/bin/python
# Demonstrates how to set permissions on the geometry service.


import httplib, urllib  # used for connecting to ArcGIS Server
import re               # used for parsing responses
import sys

def main(argv=None):

    (user,password, serverName, serverPort, role, secure) = getInputParameters()
    token = getToken(user, password, serverName, serverPort, secure)
    makeServicePrivate(serverName, serverPort, token, "Geometry", "GeometryServer")
    setServicePermission(serverName, serverPort, token, "Geometry", "GeometryServer", role)


def makeServicePublic(serverName, serverPort, token, service, serviceType):
    url = "/arcgis/admin/services/" + service + "." + serviceType + "/permissions/add"
    params = urllib.urlencode({'principal' : 'esriEveryone', 'isAllowed':'true', 'f' : 'json', 'token' : token})
    
    response = makeHttpPost(serverName, serverPort, url, params)
    if (operationSuccessful(response)) :
        print "Successfully made " + service + "." + serviceType + " public."
    else:
        print "Unable to make " + service + "." + serviceType + " public."
    

def makeServicePrivate(serverName, serverPort, token, service, serviceType):
    url = "/arcgis/admin/services/" + service + "." + serviceType + "/permissions/add"
    params = urllib.urlencode({'principal' : 'esriEveryone', 'isAllowed':'false', 'f' : 'json', 'token' : token})
    
    response = makeHttpPost(serverName, serverPort, url, params)   
    if (operationSuccessful(response)) :
        print "Successfully made " + service + "." + serviceType + " private."
    else:
        print "Unable to make " + service + "." + serviceType + " private."



def setServicePermission(serverName, serverPort, token, service, serviceType, role):
    url = "/arcgis/admin/services/" + service + "." + serviceType + "/permissions/add"
    params = urllib.urlencode({'principal' : role, 'isAllowed':'true', 'f' : 'json', 'token' : token})
    
    response = makeHttpPost(serverName, serverPort, url, params)
    if (operationSuccessful(response)) :
        print "Successfully granted " + role + " permission to " + service + "." + serviceType
    else:
        print "Unable to grant " + role + " permission to " + service + "." + serviceType


def operationSuccessful(response):
    statusPattern = re.compile('[\w]+')
    statusValue = statusPattern.findall(response)[1] 
    if (statusValue == "success"):
        return 1
    else:
        return 0

def getToken(username, password, serverName, serverPort, secure):
    tokenURL = "/arcgis/admin/generateToken"
   
    params = urllib.urlencode({'username': username, 'password': password, 'client': 'requestip', 'f': 'json'})
     
    response = makeHttpPost(serverName, serverPort, tokenURL, params, secure)
    if (response == None):
        print "ERROR: Unable to login.  The following may have caused this:"
        print 
        print "    1) Incorrect username or password."
        print "    2) Incorrect server name or port."
        if (secure):
            print "    3) The server may not have https enabled."
        print
        print
        sys.exit()
    tokenPattern = re.compile('[\w-]+')
    tokenMatch = tokenPattern.findall(response)[1]
    return tokenMatch
         
        

def makeHttpPost(serverName, serverPort, url, params, secure=0):  
    
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    if (serverPort == 80) :
        securePort = 443
    else:
        securePort = 6443
    
    try:
        httpsFailed = 0
        httpsConn = httplib.HTTPSConnection(serverName, securePort)
        httpsConn.request("POST", url, params, headers)       
        response = httpsConn.getresponse()
        if (response.status == 200):
            data = response.read()
            httpsConn.close()
            return data
        else:
            httpsFailed = 1
    except:
        httpsFailed = 1

    if (httpsFailed and secure):
        return
    
    try:
        httpConn = httplib.HTTPConnection(serverName, serverPort)
        httpConn.request("POST", url, params, headers)   
        response = httpConn.getresponse()
        if (response.status == 200):
            data = response.read()
            httpConn.close()
            return data            
        else:
            httpConn.close()
            return 
    except:
        return
   
   
def getInputParameters() :
    if (len(sys.argv)  == 1):
           print "Sets a role's permission for ArcGIS Server geometry service."
           print 
           print "     --user       Publisher/administrator user to log into ArcGIS Server with."
           print "     --password   Password for publisher/administrator login"
           print "     --server     Server machine.  Optional, default is localhost."
           print "     --port       Port to use when connecting.  Option, default 6080."
           print "     --role       ArcGIS Server role being affected."
           print "     --secure     Requires a secure login."
           print
           sys.exit()
    user = None
    password = None
    role = None
    serverName = "localhost"
    serverPort = 6080     
    secure = 0
    
    for i in range(1, len(sys.argv)) :
        if (sys.argv[i] == "--user" and i < len(sys.argv)-1):
            user = sys.argv[i+1]            
        elif (sys.argv[i] == "--password" and i < len(sys.argv)-1) :
            password = sys.argv[i+1]
        elif (sys.argv[i] == "--server" and i < len(sys.argv)-1) :
            serverName = sys.argv[i+1]
        elif (sys.argv[i] == "--port" and i < len(sys.argv)-1) :
            port = sys.argv[i+1]
        elif (sys.argv[i] == "--role" and i < len(sys.argv)-1):
            role = sys.argv[i+1]
        elif (sys.argv[i] == "--secure"):
            secure = 1
   
    if (user == None or password == None or role == None) :
        if (user == None):
            print "The --user parameter was not provided."
        elif (password == None):
            print "The --password parameter was not provided."
        elif (role == None):
            print "The --role parameter was not provided."
        sys.exit()
    else:
        return (user,password, serverName, serverPort, role, secure)
    
        
# Script start
if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
12/18/2014