Skip to content

Commit

Permalink
♻️ Replace get_auth_headers with generate_jwt util
Browse files Browse the repository at this point in the history
which can be reused in Open Zaak/Open Notificaties
  • Loading branch information
stevenbal committed Nov 8, 2024
1 parent 6c5af46 commit 8de8a6c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 30 deletions.
33 changes: 3 additions & 30 deletions tests/test_jwtsecrets.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,13 @@
import time

import jwt
import pytest
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APIClient

from vng_api_common.authorizations.models import Applicatie, Autorisatie
from vng_api_common.authorizations.utils import generate_jwt
from vng_api_common.constants import ComponentTypes
from vng_api_common.models import JWTSecret

JWT_ALG = "HS256"


def get_auth_headers(
client_id: str,
client_secret: str,
user_id: str = "",
user_representation: str = "",
**claims,
) -> dict:
payload = {
# standard claims
"iss": client_id,
"iat": int(time.time()),
# custom claims
"client_id": client_id,
"user_id": user_id,
"user_representation": user_representation,
**claims,
}

encoded = jwt.encode(payload, client_secret, algorithm=JWT_ALG)

return {"Authorization": "Bearer {encoded}".format(encoded=encoded)}


@pytest.mark.django_db
def test_unauthorized_jwtsecret_create_forbidden():
Expand All @@ -58,8 +31,8 @@ def test_authorized_jwtsecret_create_ok():
component=ComponentTypes.ac,
scopes=["autorisaties.credentials-registreren"],
)
auth_headers = get_auth_headers("pytest", "sekrit")
client.credentials(HTTP_AUTHORIZATION=auth_headers["Authorization"])
token = generate_jwt("pytest", "sekrit", "pytest", "pytest")
client.credentials(HTTP_AUTHORIZATION=token)

response = client.post(url, {"identifier": "foo", "secret": "bar"})

Expand Down
17 changes: 17 additions & 0 deletions vng_api_common/authorizations/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
def generate_jwt(client_id, secret, user_id, user_representation):
from zgw_consumers.client import ZGWAuth

class FakeService:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)

auth = ZGWAuth(
service=FakeService( # type: ignore
client_id=client_id,
secret=secret,
user_id=user_id,
user_representation=user_representation,
)
)
return f"Bearer {auth._token}"

0 comments on commit 8de8a6c

Please sign in to comment.