def get_callback_jwt(self, obj):
     if not obj.callback_client_id or not obj.callback_secret:
         return ''
     auth = ClientAuth(client_id=obj.callback_client_id,
                       secret=obj.callback_secret,
                       scopes=[SCOPE_NOTIFICATIES_CONSUMEREN_LABEL])
     return auth.credentials()['Authorization']
Exemple #2
0
    def register(self) -> None:
        """
        Registers the webhook with the notification component.
        """
        dummy_detail_url = urljoin(self.config.api_root, f'foo/{uuid.uuid4()}')
        client = Client.from_url(dummy_detail_url)

        # This authentication is to create a subscription at the NC.
        client.auth = APICredential.get_auth(
            self.config.api_root, scopes=[SCOPE_NOTIFICATIES_CONSUMEREN_LABEL])

        # This authentication is for the NC to call us. Thus, it's *not* for
        # calling the NC to create a subscription.
        self_auth = ClientAuth(client_id=self.client_id,
                               secret=self.secret,
                               scopes=[SCOPE_NOTIFICATIES_PUBLICEREN_LABEL])
        data = {
            'callbackUrl':
            self.callback_url,
            'auth':
            self_auth.credentials()['Authorization'],
            'kanalen': [
                {
                    "naam": channel,
                    # FIXME: You need to be able to configure these.
                    "filters": {},
                } for channel in self.channels
            ],
        }

        # register the subscriber
        subscriber = client.create('abonnement', data=data)

        self._subscription = subscriber['url']
        self.save(update_fields=['_subscription'])
Exemple #3
0
    def register(self) -> None:
        """
        Registers the webhook with the notification component.
        """
        dummy_detail_url = urljoin(self.config.api_root, f"foo/{uuid.uuid4()}")
        client = get_client(dummy_detail_url)

        # This authentication is for the NC to call us. Thus, it's *not* for
        # calling the NC to create a subscription.
        self_auth = ClientAuth(
            client_id=self.client_id,
            secret=self.secret,
        )
        data = {
            "callbackUrl":
            self.callback_url,
            "auth":
            self_auth.credentials()["Authorization"],
            "kanalen": [
                {
                    "naam": channel,
                    # FIXME: You need to be able to configure these.
                    "filters": {},
                } for channel in self.channels
            ],
        }

        # register the subscriber
        subscriber = client.create("abonnement", data=data)

        self._subscription = subscriber["url"]
        self.save(update_fields=["_subscription"])
def test_credentials_header():
    auth = ClientAuth(client_id="client_id", secret="secret")
    credentials = auth.credentials()

    assert "Authorization" in credentials
    parts = credentials["Authorization"].split(" ")
    assert parts[0] == "Bearer"
    def test_invalid_credentials(self):
        auth = ClientAuth(client_id="dummy", secret="secret")

        response = self.client.get(
            "/mock", HTTP_AUTHORIZATION=auth.credentials()["Authorization"])

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertFalse(User.objects.exists())
def test_client_id_in_body():
    auth = ClientAuth(client_id="client id", secret="secret")
    credentials = auth.credentials()["Authorization"]

    token = credentials.split(" ")[1]

    payload = jwt.decode(token, verify=False)

    assert "client_id" in payload
    assert "zds" not in payload
    assert payload["client_id"] == "client id"
Exemple #7
0
 def get_jwt(self, obj):
     if obj.identifier and obj.secret:
         auth = ClientAuth(obj.identifier, obj.secret)
         jwt = auth.credentials()["Authorization"]
         return format_html(
             '<code class="copy-action jwt" data-copy-value="{val}">{val}</code><p>{hint}</p>',
             val=jwt,
             hint=_(
                 "Gebruik het JWT-token nooit direct in een applicatie."),
         )
     return ""
Exemple #8
0
def test_explicit_alg():
    auth = ClientAuth("dummy", "dummy")
    credentials = auth.credentials()["Authorization"]
    token = credentials.split(" ")[1]
    header = token.split(".")[0].encode()
    # taken from django.utils.http.urlsafe_base64_decode
    decoded = base64.urlsafe_b64decode(
        header.ljust(len(header) + len(header) % 4, b"=")
    )

    jwt_header = json.loads(decoded)

    assert jwt_header["alg"] == "HS256"
Exemple #9
0
    def form_valid(self, form):
        if 'client_id' not in self.request.session:
            self.request.session['client_id'] = form.cleaned_data['client_id']
        if 'secret' not in self.request.session:
            self.request.session['secret'] = form.cleaned_data['secret']

        auth = ClientAuth(
            client_id=form.cleaned_data['client_id'],
            secret=form.cleaned_data['secret'],
        )

        self.request.session['credentials'] = auth.credentials()
        return super().form_valid(form)
Exemple #10
0
def test_client_id_in_body():
    auth = ClientAuth(client_id="client id", secret="secret")
    credentials = auth.credentials()["Authorization"]

    token = credentials.split(" ")[1]

    payload = jwt.decode(
        token,
        algorithms=["HS256"],
        options={"verify_signature": False},
    )

    assert "client_id" in payload
    assert "zds" not in payload
    assert payload["client_id"] == "client id"
Exemple #11
0
    def build_client(self, **claims):
        """
        Build an API client from the service configuration.
        """
        _uuid = uuid.uuid4()

        api_root = self.api_root
        if self.nlx:
            api_root = api_root.replace(self.api_root, self.nlx, 1)

        dummy_detail_url = f"{api_root}dummy/{_uuid}"
        Client = get_client_class()
        client = Client.from_url(dummy_detail_url)
        client.schema_url = self.oas

        if self.auth_type == AuthTypes.zgw:
            client.auth = ClientAuth(
                client_id=self.client_id,
                secret=self.secret,
                user_id=self.user_id,
                user_representation=self.user_representation,
                **claims,
            )
        elif self.auth_type == AuthTypes.api_key:
            client.auth_value = {self.header_key: self.header_value}

        return client
    def test_no_duplicate_users(self):
        ApplicationCredentials.objects.create(client_id="dummy",
                                              secret="secret")
        User.objects.create(**{User.USERNAME_FIELD: "some-user"})
        auth = ClientAuth(
            client_id="dummy",
            secret="secret",
            user_id="some-user",
            user_representation="Some User",
        )

        response = self.client.get(
            "/mock", HTTP_AUTHORIZATION=auth.credentials()["Authorization"])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(User.objects.count(), 1)
Exemple #13
0
    def get_auth(cls, url: str, **kwargs) -> Union[ClientAuth, None]:
        split_url = urlsplit(url)
        scheme_and_domain = urlunsplit(split_url[:2] + ("", "", ""))

        candidates = (
            cls.objects.filter(api_root__startswith=scheme_and_domain)
            .annotate(api_root_length=Length("api_root"))
            .order_by("-api_root_length")
        )

        # select the one matching
        for candidate in candidates.iterator():
            if url.startswith(candidate.api_root):
                credentials = candidate
                break
        else:
            return None

        auth = ClientAuth(
            client_id=credentials.client_id,
            secret=credentials.secret,
            user_id=credentials.user_id,
            user_representation=credentials.user_representation,
            **kwargs,
        )
        return auth
    def test_add_email_to_user_with_empty_email_address(self):
        ApplicationCredentials.objects.create(client_id="dummy",
                                              secret="secret")
        user = User.objects.create(**{User.USERNAME_FIELD: "some-user"})
        auth = ClientAuth(
            client_id="dummy",
            secret="secret",
            user_id="some-user",
            user_representation="Some User",
            email="*****@*****.**",
        )

        response = self.client.get(
            "/mock", HTTP_AUTHORIZATION=auth.credentials()["Authorization"])
        user = User.objects.get(**{User.USERNAME_FIELD: "some-user"})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(user.email, "*****@*****.**")
Exemple #15
0
def main():
    parser = _setup_parser()
    args = parser.parse_args()

    client_id = args.client_id
    if client_id is None:
        client_id = input("Client ID: ")
    secret = args.secret
    if secret is None:
        secret = input("Secret: ")

    auth = ClientAuth(client_id, secret)
    creds = auth.credentials()

    print("Use the following header(s) for authorization:")
    for key, value in creds.items():
        print(f"  {key}: {value}")
Exemple #16
0
def test_extra_claims():
    """
    Test that extra claims are included in the payload
    """
    auth = ClientAuth(client_id="client id", secret="secret", email="*****@*****.**")
    credentials = auth.credentials()["Authorization"]

    token = credentials.split(" ")[1]

    payload = jwt.decode(
        token,
        algorithms=["HS256"],
        options={"verify_signature": False},
    )

    assert "email" in payload
    assert payload["email"] == "*****@*****.**"
Exemple #17
0
def main():
    parser = _setup_parser()
    args = parser.parse_args()

    client_id = args.client_id
    if client_id is None:
        client_id = input("Client ID: ")
    secret = args.secret
    if secret is None:
        secret = input("Secret: ")

    extra_claims = {name: getattr(args, name) for name in parser._extras}

    auth = ClientAuth(client_id, secret, **extra_claims)
    creds = auth.credentials()

    print("Use the following header(s) for authorization:")
    for key, value in creds.items():
        print(f"  {key}: {value}")
def get_jwt(object):
    return ClientAuth(
        client_id=object.client_id,
        secret=object.secret,
        # scopes=['zds.scopes.zaken.lezen',
        #         'zds.scopes.zaaktypes.lezen',
        #         'zds.scopes.zaken.aanmaken',
        #         'zds.scopes.statussen.toevoegen',
        #         'zds.scopes.zaken.bijwerken'],
        # zaaktypes=['*']
    )
    def test_drc_subscriber_to_zaken_kanaal(self, state, nrc_client,
                                            drc_client):
        # can't add Subscription in the drc admin
        # therefore test Client.request under this command
        drc_auth = ClientAuth(
            client_id='demo',
            secret='demo',
        )

        # can't read url from spec, because it isn't added to schema
        # not working because /callbacks endpoint is not included in drc
        callback_url = '{}callbacks'.format(drc_client.base_url)

        data = {
            'callbackUrl':
            callback_url,
            'auth':
            drc_auth.credentials()['Authorization'],
            'kanalen': [{
                "naam": state.kanaal['naam'],
                "filters": {
                    "bronorganisatie": "517439943",
                    "zaaktype": "*",
                    "vertrouwelijkheidaanduiding": "*",
                }
            }],
        }

        # check if subscriber exists - for local testing:
        subs = [
            sub for sub in nrc_client.list('abonnement')
            if sub['callbackUrl'] == callback_url
        ]

        if subs:
            subscriber = subs[0]
        else:
            subscriber = nrc_client.create('abonnement', data=data)

        assert 'url' in subscriber
        state.subscriber = subscriber
    def test_valid_credentials(self):
        ApplicationCredentials.objects.create(client_id="dummy",
                                              secret="secret")
        auth = ClientAuth(
            client_id="dummy",
            secret="secret",
            user_id="some-user",
            user_representation="Some User",
            email="*****@*****.**",
        )

        response = self.client.get(
            "/mock", HTTP_AUTHORIZATION=auth.credentials()["Authorization"])

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(User.objects.count(), 1)
        user = User.objects.get()
        username = getattr(user, User.USERNAME_FIELD)
        self.assertEqual(username, "some-user")
        email = getattr(user, User.EMAIL_FIELD)
        self.assertEqual(email, "*****@*****.**")
def get_jwt(server_run):

    return ClientAuth(client_id=server_run.client_id,
                      secret=server_run.secret,
                      scopes=[
                          'zds.scopes.zaken.lezen',
                          'zds.scopes.zaaktypes.lezen',
                          'zds.scopes.zaken.aanmaken',
                          'zds.scopes.statussen.toevoegen',
                          'zds.scopes.zaken.bijwerken'
                      ],
                      zaaktypes=['*'])
Exemple #22
0
    def get_auth(cls, url: str, **kwargs) -> ClientAuth:
        split_url = urlsplit(url)
        scheme_and_domain = urlunsplit(split_url[:2] + ('', '', ''))

        candidates = (cls.objects.filter(
            api_root__startswith=scheme_and_domain).annotate(
                api_root_length=Length('api_root')).order_by(
                    '-api_root_length'))

        # select the one matching
        for candidate in candidates.iterator():
            if url.startswith(candidate.api_root):
                credentials = candidate
                break
        else:
            return None

        auth = ClientAuth(client_id=credentials.client_id,
                          secret=credentials.secret,
                          **kwargs)
        return auth