Generating Token By URL Request From ArcGIS Portal?

340
1
03-26-2020 01:10 AM
Esri Contributor

Hi,

I'm trying to generate a token from a Portal url. It generates a token when pasting this link into a web browser:

https://portalUrl/sharing/rest/generateToken?&f=json 

but when I run this code:

function getToken(portalUrl, username, password) {
var xmlhttp = new XMLHttpRequest();
var url = "https://portalUrl/sharing/rest/generateToken?username=username&password=password&f=json";


xmlhttp.open("POST", url, false);
xmlhttp.send();

if (xmlhttp.status == 200) {
var responseJSON = JSON.parse(xmlhttp.responseText)
if (responseJSON && !responseJSON.error) {
return responseJSON.token;
} else {
return "ERROR";
}
} else {
return "ERROR"
}
}

I get an error.

and I've created this in XHR code too:

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});

xhr.open("POST", "https://portalUrl/sharing/rest/generateToken?username=username&password=password&f=json");

xhr.send();

and this throws the following error:

{"error":{"code":400,"message":"Unable to generate token.","details":["POST request should not contain username and password in the query string."]}}

Any ideas or help is appreciated.

Thank you.

Tags (1)
Reply
0 Kudos
1 Reply
Esri Esteemed Contributor

Hi Mehdi,

If you have Windows Authentication enabled on the web adaptor, you will need to go around the web adaptor and specify the server name where portal is installed (i.e. server.domain.com:7443/arcgis). Ex:

import requests, json

# Disable warnings
requests.packages.urllib3.disable_warnings()

username = "gis\jskinner"
password = "********"

tokenURL = 'https://server.domain.com:7443/arcgis/sharing/rest/generateToken/'
params = {'f': 'pjson', 'username': username, 'password': password, 'referer': 'https://server.domain.com'}

r = requests.post(tokenURL, data = params, verify=False)
response = json.loads(r.content)
token = response['token']
print(token)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

If Windows Authentication is not enabled, you specify the web adaptor URL (i.e. server.domain.com/portal):

import requests, json

# Disable warnings
requests.packages.urllib3.disable_warnings()

username = "gis\jskinner"
password = "********"

tokenURL = 'https://server.domain.com/portal/sharing/rest/generateToken/'
params = {'f': 'pjson', 'username': username, 'password': password, 'referer': 'https://server.domain.com'}

r = requests.post(tokenURL, data = params, verify=False)
response = json.loads(r.content)
token = response['token']
print(token)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
Reply
0 Kudos