Search code examples
pythondjangodjango-rest-frameworkdjango-rest-framework-simplejwt

Importing Signing and Verifying key for JWT RSA algorithm in Django rest framework


I'm working on a django rest api application that uses JWTAuthentication using django-rest-framework-simplejwt. Since the RSA algorithm is in use, the signing and verifying key needs to be set.

The implementation below worked for me.

SIMPLE_JWT = {
    'SIGNING_KEY': open('jwtRS256.key').read() if os.path.isfile('./jwtRS256.key') else None,
    'VERIFYING_KEY': open('jwtRS256.key.pub').read() if os.path.isfile('./jwtRS256.key.pub') else None,
}

After upgrading to django 3 and running py -Wa manage.py test. This are some of the warning messages being displayed.

D:\path\to\settings.py:398: ResourceWarning: unclosed file <_io.TextIOWrapper name='jwtRS256.key' mode='r' encoding='cp1252'>
  'SIGNING_KEY': open('jwtRS256.key').read() if os.path.isfile('./jwtRS256.key') else None,
ResourceWarning: Enable tracemalloc to get the object allocation traceback
D:\path\to\\settings.py:399: ResourceWarning: unclosed file <_io.TextIOWrapper name='jwtRS256.key.pub' mode='r' encoding='cp1252'>
  'VERIFYING_KEY': open('jwtRS256.key.pub').read() if os.path.isfile('./jwtRS256.key.pub') else None,
ResourceWarning: Enable tracemalloc to get the object allocation traceback

I tried an alternative to solve this issue but it seems to break the app when authenticating users. This is the attempted solution.

def get_file(file_url):
    if os.path.isfile(file_url):
        with open(file_url) as f:
            return f
            
    return None


SIMPLE_JWT = {
    'SIGNING_KEY': get_file('./jwtRS256.key'),
    'VERIFYING_KEY': get_file('./jwtRS256.key.pub')
}

This doesn't work when trying to log in and returns a 500 with TypeError: Expecting a PEM-formatted key.


Solution

  • My bad. I forgot to read the file.

    def get_file(file_url):
        if os.path.isfile(file_url):
            with open(file_url) as f:
                return f.read()
    
        return None