jpadilla / django-rest-framework-jwt

JSON Web Token Authentication support for Django REST Framework
http://jpadilla.github.io/django-rest-framework-jwt/
MIT License
3.19k stars 652 forks source link

Help configuring JWT_PRIVATE_KEY/JWT_PUBLIC_KEY #394

Closed zemanel closed 6 years ago

zemanel commented 6 years ago

I'm utilising django-rest-framework-jwt for an REST API authentication and i'd like to have the same web token authorize access to another http service (couchdb).

For creating a JWT enabled reverse proxy i'm looking at jwtproxy (https://github.com/coreos/jwtproxy) which 8afaik) can use a preshared RSA key, so i'm trying to configure RSA private/public keys on django-rest-framework-jwt.

Docs mention JWT_PUBLIC_KEYis an object of type cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey and i'm utilising cryptography to try and load an private key file (https://github.com/coreos/jwtproxy/blob/master/examples/httpserver/mykey.key):

def load_private_key(filepath):
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend
    with open(filepath, "rb") as key_file:
        private_key = serialization.load_pem_private_key(key_file.read(), password=None, backend=default_backend())
    return private_key

private_key = load_private_key('../../jwtproxy/examples/httpserver/mykey.key')

JWT_AUTH = {
    'JWT_ALLOW_REFRESH': True,
    'JWT_PRIVATE_KEY': private_key,
    'JWT_PUBLIC_KEY': private_key.public_key(),
    'JWT_ALGORITHM': 'HS256'
}

But i get an error about key not being a string type

value = <cryptography.hazmat.backends.openssl.rsa._RSAPrivateKey object at 0x10ca57f60>

    def force_bytes(value):
        if isinstance(value, text_type):
            return value.encode('utf-8')
        elif isinstance(value, binary_type):
            return value
        else:
>           raise TypeError('Expected a string value')
E           TypeError: Expected a string value

If i convert the key objet to bytes:

private_key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.PKCS1)

i get an exception about the key format:

jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.

Could i get a nudge in the right direction on how to set proper values for JWT_PRIVATE_KEY/JWT_PUBLIC_KEY from a RSA key ?

and3rson commented 6 years ago

I'm having the same issue.

brussee commented 6 years ago

Instead of 'JWT_ALGORITHM': 'HS256' put 'JWT_ALGORITHM': 'RS256'.

edit: See https://stackoverflow.com/questions/39239051/rs256-vs-hs256-whats-the-difference

zemanel commented 6 years ago

@brussee i changed the algorithm at the time to 'RS256' and worked perfectly, thanks