Tôi đang cố triển khai xác thực HMAC-SHA256 vào dự án API RESTful Python của mình. Tôi đang sử dụng Python Eve [được xây dựng trên Flask], bắt đầu bằng một ví dụ HMAC-SHA1 đơn giản hóa
Ứng dụng của tôi rất đơn giản
##
# application.py
##
from eve import Eve
from hmac import HMACAuth
SETTINGS = {
'DEBUG': True,
'MONGO_HOST': '127.0.0.1',
'MONGO_PORT': 27017,
'MONGO_DBNAME': 'testing',
'DOMAIN': {'test': {}},
}
app = Eve[auth=HMACAuth, settings=SETTINGS]
if __name__ == '__main__':
app.run[use_reloader=True]
và lớp HMACAuth
##
# hmac.py
##
import time
import hmac
from eve.auth import HMACAuth
from flask import current_app as app
from hashlib import sha256
class HMACAuth[HMACAuth]:
def check_auth[self, userid, hmac_hash, headers, data, allowed_roles, resource, method]:
# get user from database
accounts = app.data.driver.db['accounts']
user = accounts.find_one[{'userid': userid}]
if user:
# user found, we have its secret_key and we can re-create the signature user sent us
check_sig = hmac.new[bytes[user['secret_key'], 'utf8'], b'', sha256]
check_sig.update[bytes[headers['TIMESTAMP'], 'utf-8']]
check_sig.update[data]
check_signature = check_sig.hexdigest[]
# try to use python's hmac.compare_digest[] to compare user's signature
# and the one we re-created
if hmac.compare_digest[check_signature, hmac_hash]:
# signature seems fine, we have to check if the request was sent in past 30 seconds
# we are also checking for negative time because we have a test case with timestamp
# in the future, so time_diff ends up with a negative number
time_diff = int[time.time[]] - int[headers['TIMESTAMP']]
if 0