I'm just learning to work with functions and now classes in python. The functions that i've created would work if they were not in a class, but now my objective is to create a class for them. It looks like I'm not understanding how self
works. I've added it as a parameter for each function, however I'm running into NameError: name 'variable name' is not defined
messages when calling the functions. What am I missing?
Here is the script myTokClassTst.py
code in progress:
import time
import json
import jwt
import requests
from lib.jwksutils import rsa_pem_from_jwk
class TokenMgr():
"""An attempt to model a Token Manager"""
def __init__(self):
"""Initialize token attributes as needed"""
pass
def get_kid(self, token):
headers = jwt.get_unverified_header(token)
if not headers:
raise InvalidAuthorizationToken('missing headers')
try:
return headers['kid']
except KeyError:
raise InvalidAuthorizationToken('missing kid')
def get_jwk(self, kid):
with open('testkeys/jwks-keys', 'r') as az:
jwks = json.load(az)
for jwk in jwks.get('keys'):
if jwk.get('kid') == kid:
print ('This is the jwk:', jwk)
return jwk
raise InvalidAuthorizationToken('kid not recognized')
def get_public_key(self, token):
print ('Response from get_public_token:', rsa_pem_from_jwk(get_jwk(get_kid(token))) )
return rsa_pem_from_jwk(get_jwk(get_kid(token)))
def validate_jwt(self, jwt_to_validate):
public_key = get_public_key(jwt_to_validate)
#Hard coding these for now
valid_audiences = ['abc123aa86-1f3a-4774-8bae-2704bff9f797']
issuer = 'https://login.microsoftonline.com/99c77bbe-8598-4b85-9e51-1ca753fa50f2/v2.0'
decoded = jwt.decode(jwt_to_validate,
public_key,
verify=True,
algorithms=['RS256'],
audience=valid_audiences,
issuer=issuer)
print('This is decoded:', decoded)
I'm calling the function like so within a python shell:
$ python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import myTokClassTst as mytok
>>> idval = mytok.TokenMgr()
>>> idval.validate_jwt('eyJ0eXAiOiJKV1QiLCJhbGciOiJSUA')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\myTokClassTst.py", line 97, in validate_jwt
public_key = get_public_key(jwt_to_validate)
NameError: name 'get_public_key' is not defined