Search code examples
pythonoauthevernote

Evernote access token Python


I am trying to retrieve Evernote OAuth access token through Python by following the documentation here. However, multiple attempts, I am not able to retrieve the temporary access token which is the very first step in this 3 legged authorization.

Any idea what am I doing wrong here?

import time
import base64
import random
import uuid
import urllib
import collections
import urllib.parse
import hmac
import hashlib
import binascii
import requests

def escape(s):
    return urllib.parse.quote(s, safe='~')
def get_nonce():
    return uuid.uuid4().hex

def stringify_parameters(parameters):
    output = ''
    ordered_parameters = {}
    ordered_parameters =     
    collections.OrderedDict(sorted(parameters.items()))

    counter = 1
    for k, v in ordered_parameters.items():
        output += escape(str(k)) + '=' + escape(str(v))
        if counter < len(ordered_parameters):
           output += '&'
           counter += 1

    return output

oauth_parameters={
'oauth_timestamp': str(int(time.time())),
'oauth_signature_method': "HMAC-SHA1",
'oauth_version': "1.0",
'oauth_nonce': get_nonce(),
'oauth_consumer_key': 'consumerkey',
'oauth_callback':'http://localhost'
}

string_parameters=stringify_parameters(oauth_parameters)
secret='secret'

signature = hmac.new(secret.encode(), string_parameters.encode(),hashlib.sha1).digest()
oauth_parameters['oauth_signature']=escape(base64.b64encode(signature).decode())

res=requests.get('https://sandbox.evernote.com/oauth?'+stringify_parameters(oauth_parameters))

print(res.status_code)

Solution

  • I think the way you create a signature is incorrect. This works for me:

    key = (escape(secret)+'&').encode()
    message = ('GET&' + escape('https://sandbox.evernote.com/oauth') + '&' + escape(string_parameters)).encode()
    signature = hmac.new(key, message, hashlib.sha1).digest()
    oauth_parameters['oauth_signature'] = base64.b64encode(signature).decode()
    
    res = requests.get('https://sandbox.evernote.com/oauth?' + stringify_parameters(oauth_parameters))