token_utils.py 4.14 KB
Newer Older
1
"""Utilities for working with ID tokens."""
2
import json
3
from time import time
4

5
from Cryptodome.PublicKey import RSA
6
from django.conf import settings
7
from django.utils.functional import cached_property
8 9
from jwkest.jwk import KEYS, RSAKey
from jwkest.jws import JWS
10

11
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
12
from student.models import UserProfile, anonymous_id_for_user
13 14


15 16
class JwtBuilder(object):
    """Utility for building JWTs.
17

18 19
    Unifies diverse approaches to JWT creation in a single class. This utility defaults to using the system's
    JWT configuration.
20

21 22
    NOTE: This utility class will allow you to override the signing key and audience claim to support those
    clients which still require this. This approach to JWT creation is DEPRECATED. Avoid doing this for new clients.
23 24 25

    Arguments:
        user (User): User for which to generate the JWT.
26

27 28 29
    Keyword Arguments:
        asymmetric (Boolean): Whether the JWT should be signed with this app's private key.
        secret (string): Overrides configured JWT secret (signing) key. Unused if an asymmetric signature is requested.
30
    """
31

32 33 34 35
    def __init__(self, user, asymmetric=False, secret=None):
        self.user = user
        self.asymmetric = asymmetric
        self.secret = secret
36
        self.jwt_auth = configuration_helpers.get_value('JWT_AUTH', settings.JWT_AUTH)
37

38
    def build_token(self, scopes, expires_in=None, aud=None, additional_claims=None):
39 40 41 42 43 44
        """Returns a JWT access token.

        Arguments:
            scopes (list): Scopes controlling which optional claims are included in the token.

        Keyword Arguments:
45
            expires_in (int): Time to token expiry, specified in seconds.
46
            aud (string): Overrides configured JWT audience claim.
47 48 49 50
            additional_claims (dict): Additional claims to include in the token.

        Returns:
            str: Encoded JWT
51 52
        """
        now = int(time())
53
        expires_in = expires_in or self.jwt_auth['JWT_EXPIRATION']
54
        payload = {
55
            # TODO Consider getting rid of this claim since we don't use it.
56 57 58 59 60 61 62 63 64
            'aud': aud if aud else self.jwt_auth['JWT_AUDIENCE'],
            'exp': now + expires_in,
            'iat': now,
            'iss': self.jwt_auth['JWT_ISSUER'],
            'preferred_username': self.user.username,
            'scopes': scopes,
            'sub': anonymous_id_for_user(self.user, None),
        }

65 66 67
        if additional_claims:
            payload.update(additional_claims)

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
        for scope in scopes:
            handler = self.claim_handlers.get(scope)

            if handler:
                handler(payload)

        return self.encode(payload)

    @cached_property
    def claim_handlers(self):
        """Returns a dictionary mapping scopes to methods that will add claims to the JWT payload."""

        return {
            'email': self.attach_email_claim,
            'profile': self.attach_profile_claim
        }

    def attach_email_claim(self, payload):
        """Add the email claim details to the JWT payload."""
        payload['email'] = self.user.email

    def attach_profile_claim(self, payload):
        """Add the profile claim details to the JWT payload."""
        try:
            # Some users (e.g., service users) may not have user profiles.
            name = UserProfile.objects.get(user=self.user).name
        except UserProfile.DoesNotExist:
            name = None

        payload.update({
            'name': name,
99 100
            'family_name': self.user.last_name,
            'given_name': self.user.first_name,
101 102 103 104 105
            'administrator': self.user.is_staff,
        })

    def encode(self, payload):
        """Encode the provided payload."""
106 107
        keys = KEYS()

108
        if self.asymmetric:
109
            keys.add(RSAKey(key=RSA.importKey(settings.JWT_PRIVATE_SIGNING_KEY)))
110 111
            algorithm = 'RS512'
        else:
112 113
            key = self.secret if self.secret else self.jwt_auth['JWT_SECRET_KEY']
            keys.add({'key': key, 'kty': 'oct'})
114 115
            algorithm = self.jwt_auth['JWT_ALGORITHM']

116 117 118
        data = json.dumps(payload)
        jws = JWS(data, alg=algorithm)
        return jws.sign_compact(keys=keys)