繁体   English   中英

在 Django rest 框架中导入 JWT RSA 算法的签名和验证密钥

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

我正在开发一个使用 JWTAuthentication using django-rest-framework-simplejwt的 django rest api 应用程序。 由于使用的是 RSA 算法,所以需要设置签名和验证密钥。

下面的实现对我有用。

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,
}

升级到 django 3 并运行py -Wa manage.py test后。 这是正在显示的一些警告消息。

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

我尝试了一种替代方法来解决这个问题,但在验证用户时它似乎破坏了应用程序。 这是尝试的解决方案。

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')
}

这在尝试登录并返回 500 时不起作用, TypeError: Expecting a PEM-formatted key.

我的错。 我忘记阅读文件了。

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

    return None

你可以试试这样

def get_file(file_url):
     file_path = os.path.join(settings.MEDIA_ROOT, file_url)    
     if os.path.exists(file_path):
        with open(file_path,'rb') as f:
            return f.read()

    return None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM