Category Archives: Python

How to generate X-WSSE Token using Python

Learn how to generate X-WSSE Token and how to authorize requests using X-WSSE header authentication.

If you’re not familiar with X-WSSE Token Authentication and why you should use it, go ahead and read this article that contains the basics of this type of authentication.

In this article I’ll describe how to generate a X-WSSE Token using Python.

import datetime
import hashlib
import random
import base64
 
def getWsseHeader(username, secret):
    created = datetime.datetime.utcnow().isoformat();
    nonce = hashlib.md5(str(random.getrandbits(128)).encode('utf-8')).hexdigest()
    digest = "".join((nonce, created, secret))
    digest = hashlib.sha256(digest.encode('utf-8')).hexdigest()
    digest = base64.b64encode(digest.encode("utf-8")).decode('utf-8')
    return ('UsernameToken Username="{username}", '
            'PasswordDigest="{digest}", Nonce="{nonce}", '
            'Created="{created}"').format(username=username,
                                        digest=digest,
                                        nonce=nonce,
                                        created=created)
 
xwsse = getWsseHeader("CLIENT_ID", "CLIENT_SECRET");
print(xwsse)

That’s it. Check my other X-WSSE Articles and learn how to generate the token using other programming languages.