Ejemplo n.º 1
0
def verify_token(token):
    '''
    Verify that:
        We
    :param token: jwt token (as bytes)
    :return: type(get_user_model())
    '''
    # use sha256 to reduce key size
    token_sha = sha256(token.encode('utf-8')).hexdigest()

    # Check to see if this token is in the cache
    # we set TTL when we insert, so its existence means it hasn't expired
    # If it exists in the cache, we don't need to verify it
    verify = not cache.get(token_sha)

    # If token DNE in cache, we need to verify it first
    # In the case that the token isn't cached, we need to decode and verify the signature
    # In the case that it is in the cache, we need to decode to get the 'sub' and 'iss' claims to look up the user
    claims = jwt.decode(
        token=token,
        verify=verify,
        audience=settings.DJANGO_JWTAUTH['JWT_AUDIENCE'],
        issuer=settings.DJANGO_JWTAUTH['JWT_ISSUER'],
        key=get_public_key(),
        algorithms=[settings.DJANGO_JWTAUTH['JWT_ALGORITHM']]
    )

    user_id_claim = None
    if 'sub' in claims:
        user_id_claim = 'sub'
    elif 'azp' in claims:
        user_id_claim = 'azp'
    else:
        raise exceptions.MissingRequiredClaimError('Either "sub" or "azp" must be set.')

    # If it's a valid token from an issuer we trust, we need to see if there's a user record associated
    try:
        # Now we check to see whether we have a user in our local db
        # that corresponds to the subject and issuer ('sub', 'azp', 'iss') claims in our token
        remote_user = RemoteUser.objects.get(sub=claims[user_id_claim], iss=claims['iss'])

    except RemoteUser.DoesNotExist:
        # if the user isn't found, we'll hit here
        # Not having a remote user user means that we don't have a local user,
        # so we'll create done of each
        local_user = get_user_model().objects.create()
        remote_user = RemoteUser.objects.create(
            sub=claims[user_id_claim],
            iss=claims['iss'],
            local_user=local_user
        )

    # If we get here, the user exists in the db, so we add their token to the cache
    if verify:
        cache.set(token_sha, 1, max(0, int(claims['exp'] - time())))

    return remote_user.local_user
Ejemplo n.º 2
0
def check_mandatory_claims(payload, claims=MANDATORY_CLAIMS):
    """Check dict for mandatory claims."""
    for claim in claims:
        if claim not in payload:
            raise exceptions.MissingRequiredClaimError(claim)