'error': {'code': 498, 'message': 'Invalid Token'

860
10
Jump to solution
12-07-2020 03:34 AM
Clive_S
New Contributor III

I used the ESRI Python token code sample, which returns a token.

However when I use the token in <url+token>, I get an error??

formatted_json = [feature['attributes'] for feature in raw_json['features']]
KeyError: 'features'
{'error': {'code': 498, 'message': 'Invalid Token', 'details': []}}

 

The code is:

ef get_token():
    params = {'username': username, 'password': password, 'expiration': str(60), 'client': 'referer', 'referer': referer, 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret,   'f': 'json'}
    request = requests.get(token_url, params=params)
    response = request.json()
    #print(response)
    token = response['access_token']
    return token

portalToken = get_token()
#### THIS works + returns Token
#print(portalToken)
##print("END")

if __name__ == "__get_token__":
    """optional location for parameters"""
    print(sys.argv[0])

 The get_token returns a token.. they all seem to have .. at the end of the token?? This is really frustrating, would appreciate any pointers!!

Thanks,

Clive

 

Tags (3)
Reply
0 Kudos
1 Solution

Accepted Solutions
DavidPike
MVP Regular Contributor

OK.

Assuming username, password and url parameters are correct, your request seems to be missing headers - headers = {'content-type': 'application/x-www-form-urlencoded'}

are you passing the url as url = portalUrl + '/sharing/rest/generateToken?'

Also can't see the parameters of clientid secret and granttype.

 

import requests


portalUrl = "https://domain/portal"
username = 'username'
password = "password"


def generateToken(username, password, portalUrl):
    # Retrieves a token to be used with API requests.
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    parameters = {'username': username,
                  'password': password,
                  'client': 'referer',
                  'referer': portalUrl,
                  'expiration': 60,
                  'f': 'json'}
    url = portalUrl + '/sharing/rest/generateToken?'
    response = requests.post(url, data=parameters, headers=headers)

    try:
        jsonResponse = response.json()
        
        if 'token' in jsonResponse:
            return jsonResponse['token']
        elif 'error' in jsonResponse:
            print (jsonResponse['error']['message'])
            for detail in jsonResponse['error']['details']:
                print (detail)
    except ValueError:
        print('An unspecified error occurred.')
        print(ValueError)


        
token = generateToken(username, password, portalUrl)

 

 

View solution in original post

10 Replies
Clive_S
New Contributor III

I changed

 the get to post, still getting invalid token error.

request = requests.get(token_url, params=params)

to
request = requests.post(token_url, params=params)

 

Reply
0 Kudos
DavidPike
MVP Regular Contributor

what does the query url look like with the token appended? do you have:

"&token=" + token

request.get(https://blablabla?f=json&token=hfwjfjkewkjfwkfjk..

Clive_S
New Contributor III

Hi David,

Thanks for the reply.

I updated the code, got a more useful error.... I think??

 

def get_token(url, username, password):
    ''' use this to get a token from arcgis online '''
    gen_token_url = token_url
    # payload params for the post request
    params = {'username':username, 'password':password,'client':'referer', 'referer':url, 'client_id': client_id, 'client_secret': client_secret, 'grant_type': grant_type, 'expiration':expiration, 'f':'json'}

    response = requests.post(gen_token_url, data=params, verify=False)
    data = response.json() # convert to json
    print('access_token')
    #return data['access_token']

mytoken = get_token(url, username, password)

if __name__ == "__get_token__":
    """optional location for parameters"""
    print(sys.argv[0])

 

I added: client_id, 'client_secret': client_secret, 'grant_type': grant_type

 

Now I am getting  a new error: InsecureRequestWarning: Unverified HTTPS request.

redirect_uri not specified

 

I don't want users to login!!  I want to get a token to login

Reply
0 Kudos
DavidPike
MVP Regular Contributor

Yep, again, what is the request you're attempting?

Reply
0 Kudos
Clive_S
New Contributor III

Hi David.

I need to automate getting the Token.

The previous code returned a Token, but threw an invalid Token error consuming the REST end point (json = URL+Token).

I have a rest endpoint and URL.

If I go to  'https://mycomp.maps.arcgis.com/sharing/rest/oauth2/token', this provides a Token

Then if I use: json_file = url+token, this returns JSON.

Is this clearer??

Reply
0 Kudos
DavidPike
MVP Regular Contributor

what i mean is that since the issue seems to be the format of the post or get to your rest endpoint, it would be helpful to share what it looks like.

Reply
0 Kudos
Clive_S
New Contributor III

Hi David,

In the code:

 

#def get_token(url, username, password):
def get_token():
    ''' use this to get a token from arcgis online '''
    gen_token_url = token_url
    # payload params for the post request
    params = {'username':username, 'password':password,'client':'referer', 'referer':url, 'client_id': client_id, 'client_secret': client_secret, 'grant_type': grant_type, 'expiration':expiration, 'f':'json'}

    response = requests.post(gen_token_url, data=params, verify=False)
    data = response.json() # convert to json
    return data['access_token']

mytoken = get_token()
print(get_token) <<<  warning

 

 

The warning is:

 

The error/warnig:
C:\Users\user\anaconda3\python.exe C:/Users/user/PycharmProjects/pythonProject1/Test.py
C:\Users\user\anaconda3\lib\site-packages\urllib3\connectionpool.py:979: InsecureRequestWarning: Unverified HTTPS request is being made to host 'eiffagekier.maps.arcgis.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  warnings.warn(

InsecureRequestWarning: Unverified HTTPS request is being made to host

 

 

Reply
0 Kudos
Clive_S
New Contributor III

Hi David,

I thought that stated at the beginning of the post that if I create a Token using the Portal Form.GenerateToken.PNG

 Then use that token in the REST url.

json_file = url+token, this returns the JSON. The issue that I have is trying to generate a Token.

This returns the error message/s.

Reply
0 Kudos
DavidPike
MVP Regular Contributor

OK.

Assuming username, password and url parameters are correct, your request seems to be missing headers - headers = {'content-type': 'application/x-www-form-urlencoded'}

are you passing the url as url = portalUrl + '/sharing/rest/generateToken?'

Also can't see the parameters of clientid secret and granttype.

 

import requests


portalUrl = "https://domain/portal"
username = 'username'
password = "password"


def generateToken(username, password, portalUrl):
    # Retrieves a token to be used with API requests.
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    parameters = {'username': username,
                  'password': password,
                  'client': 'referer',
                  'referer': portalUrl,
                  'expiration': 60,
                  'f': 'json'}
    url = portalUrl + '/sharing/rest/generateToken?'
    response = requests.post(url, data=parameters, headers=headers)

    try:
        jsonResponse = response.json()
        
        if 'token' in jsonResponse:
            return jsonResponse['token']
        elif 'error' in jsonResponse:
            print (jsonResponse['error']['message'])
            for detail in jsonResponse['error']['details']:
                print (detail)
    except ValueError:
        print('An unspecified error occurred.')
        print(ValueError)


        
token = generateToken(username, password, portalUrl)

 

 

View solution in original post