步骤 2. 编码扩展
2.1 现在,让我们编写一个简单的扩展程序。对于此场景,假设我们要求客户 zip 代码为 '12345',否则扩展将失败。如果验证通过,扩展还将使用 country 'US' 丰富客户参数文件。
我们将使用 Python 对扩展进行编码。我们将仅涵盖与我们的需求相关的代码块。完整代码将在本节末尾提供。
2.1.1 首先,我们从 HTTP 请求标头检索 JWT 持有者令牌
1234567
auth_header = request.get_header('Authorization')
if auth_header and auth_header.startswith('bearer '):
bearer = auth_header[7:]
else:
return err('Bearer token absent or invalid!')
2.1.2 然后,我们从持有者令牌的 标头中恢复密钥标识(kid 属性)。
1234567
try:
header = jwt.get_unverified_header(bearer)
kid = header['kid']
except jwt.exceptions.PyJWTError as e:
return err('Invalid token header: ' + str(e))
2.1.3 我们获得 JWK 格式的 SAP Customer Data Platform 公钥列表。在该清单中,我们在上一步中找到与 kid 相对应的键值。
123456789101112131415
try:
response = requests.get('https://accounts.us1.gigya.com/accounts.getJWTPublicKey?v2=true')
keys = response.json()
except requests.exceptions.RequestException as e:
return err('Unable to retrieve SAP CDP Public Keys: ' + str(e))
for key in keys['keys']:
if (kid == key['kid']):
public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(key))
break
if not public_key:
return err('No SAP CDP Public Key for kid ' + kid)
2.1.4 我们现在验证持有者令牌。此步骤对于安全至关重要,可阻止并非源自 SAP Customer Data Platform 服务器的任何请求。
123456
try:
token_payload = jwt.decode(bearer, key=public_key, algorithms=['RS256'])
except jwt.exceptions.PyJWTError as e:
return err('Invalid bearer token ' + bearer + '. Reason: ' + str(e))
2.1.5 验证颁发者(持有者令牌有效负载中的 iss 属性)是否与业务单位标识匹配。将 <BU_ID> 占位符替换为您自己的业务单位标识。
注意:可以在 /business_unit/ 部分后斜线之间的 URL 路径上的浏览器地址栏中找到业务单位标识。
123456
EXPECTED_ISS = 'https://fidm.gigya.com/jwt/<BU_ID>/'
iss = token_payload['iss']
if iss != EXPECTED_ISS:
return err('Invalid iss ' + iss)
2.1.6 下一个块实施我们的业务需求。在扩展请求有效负载中,在属性 data.zip 中找到邮政编码。如果邮政编码不是 '12345',则扩展执行失败。
123456
request_payload = request.json
zipcode = request_payload['data']['zip']
if zipcode != '12345':
return err('Invalid zip ' + zipcode)
2.1.7 最后,返回 HTTP 200 OK 状态(成功)。扩展响应有效负载的状态为 OK,并使用 country 'US' 属性值 (data.extension.country) 丰富原始事件记录。
12345678910111213141516
status = 200
message = {
'status': 'OK',
'data': {
'extension': {
'country': 'US'
}
},
'errorMessage': ''
}
headers = {
'Content-Type': 'application/json'
}
return HTTPResponse(body=json.dumps(message), status=status, headers=headers)
2.1.8 您可能发现帮助程序函数 err 在验证失败时被调用。我们来看一下它的代码。它基本上返回 HTTP 200 OK 状态(成功)、状态 fail 和 errorMessage 作为函数参数 msg(由函数调用者提供)。
123456789101112
def err(msg):
status = 200
headers = {
'Content-Type': 'application/json'
}
message = {
'status': 'fail',
'errorMessage': msg
}
return HTTPResponse(body=json.dumps(message), status=status, headers=headers)
注意
注意:如果我们未能通过扩展的响应,您可能会想知道为什么 HTTP 状态仍为 200。这是因为无论实际的扩展响应状态如何,始终返回 HTTP 200 状态都很重要。HTTP 200 状态告知 SAP Customer Data Platform REST 端点正常,验证失败不在系统或基础架构级别,而是在应用程序级别(扩展服务器端代码)。
2.1.9 请参阅此处的完整扩展代码。如果您决定复制并粘贴,只需确保使用与自己的业务单位标识相对应的 iss URL(请参阅上面的步骤 2-e)。
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
import requests
import json
import jwt
import bottle
from bottle import HTTPResponse
def err(msg):
status = 200
headers = {
'Content-Type': 'application/json'
}
message = {
'status': 'fail',
'errorMessage': msg
}
return HTTPResponse(body=json.dumps(message), status=status, headers=headers)
def main(url):
request = bottle.request
auth_header = request.get_header('Authorization')
if auth_header and auth_header.startswith('bearer '):
bearer = auth_header[7:]
else:
return err('Bearer token absent or invalid!')
try:
header = jwt.get_unverified_header(bearer)
kid = header['kid']
except jwt.exceptions.PyJWTError as e:
return err('Invalid token header: ' + str(e))
try:
response = requests.get('https://accounts.us1.gigya.com/accounts.getJWTPublicKey?v2=true')
keys = response.json()
except requests.exceptions.RequestException as e:
return err('Unable to retrieve SAP CDP Public Keys: ' + str(e))
for key in keys['keys']:
if (kid == key['kid']):
public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(key))
break
if not public_key:
return err('No SAP CDP Public Key for kid ' + kid)
try:
token_payload = jwt.decode(bearer, key=public_key, algorithms=['RS256'])
except jwt.exceptions.PyJWTError as e:
return err('Invalid bearer token ' + bearer + '. Reason: ' + str(e))
EXPECTED_ISS = 'https://fidm.gigya.com/jwt/4_iNfbhGDrBGciUrxckeBfJA/'
iss = token_payload['iss']
if iss != EXPECTED_ISS:
return err('Invalid iss ' + iss)
request_payload = request.json
zipcode = request_payload['data']['zip']
if zipcode != '12345':
return err('Invalid zip ' + zipcode)
status = 200
message = {
'status': 'OK',
'data': {
'extension': {
'country': 'US'
}
},
'errorMessage': ''
}
headers = {
'Content-Type': 'application/json'
}
return HTTPResponse(body=json.dumps(message), status=status, headers=headers)
if __name__ == '__main__':
bottle.route('/<url:re:.+>', ['GET', 'POST'], main)
bottle.run(host='localhost', port=8080, debug=True)