def test_pre_auth_approval_prompt(self):
     tok = AccessToken.objects.create(user=self.test_user,
                                      token="1234567890",
                                      application=self.application,
                                      expires=timezone.now() +
                                      datetime.timedelta(days=1),
                                      scope="read write")
     self.client.login(username="******", password="******")
     query_string = urlencode({
         "client_id": self.application.client_id,
         "response_type": "code",
         "state": "random_state_string",
         "scope": "read write",
         "redirect_uri": "http://example.org",
         "approval_prompt": "auto",
     })
     url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"),
                               qs=query_string)
     response = self.client.get(url)
     self.assertEqual(response.status_code, 302)
     # user already authorized the application, but with different scopes: prompt them.
     tok.scope = "read"
     tok.save()
     response = self.client.get(url)
     self.assertEqual(response.status_code, 200)
Exemplo n.º 2
0
    def test_id_token_skip_authorization_completely_missing_nonce(self):
        """
        If application.skip_authorization = True, should skip the authorization page.
        """
        self.client.login(username="******", password="******")
        self.application.skip_authorization = True
        self.application.save()

        query_string = urlencode({
            "client_id": self.application.client_id,
            "response_type": "id_token",
            "state": "random_state_string",
            "scope": "openid",
            "redirect_uri": "http://example.org",
        })

        url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"),
                                  qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)
        self.assertIn("error=invalid_request", response["Location"])
        self.assertIn(
            "error_description=Request+is+missing+mandatory+nonce+paramete",
            response["Location"])
    def test_pre_auth_valid_client_custom_redirect_uri_scheme(self):
        """
        Test response for a valid client_id with response_type: code
        using a non-standard, but allowed, redirect_uri scheme.
        """
        self.client.login(username="******", password="******")

        query_string = urlencode({
            "client_id": self.application.client_id,
            "response_type": "code",
            "state": "random_state_string",
            "scope": "read write",
            "redirect_uri": "custom-scheme://example.com",
        })
        url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"),
                                  qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        # check form is in context and form params are valid
        self.assertIn("form", response.context)

        form = response.context["form"]
        self.assertEqual(form["redirect_uri"].value(),
                         "custom-scheme://example.com")
        self.assertEqual(form["state"].value(), "random_state_string")
        self.assertEqual(form["scope"].value(), "read write")
        self.assertEqual(form["client_id"].value(), self.application.client_id)
    def test_pre_auth_valid_client(self):
        """
        Test response for a valid client_id with response_type: code
        """
        self.client.login(username="******", password="******")

        query_string = urlencode({
            'client_id': self.application.client_id,
            'response_type': 'code',
            'state': 'random_state_string',
            'scope': 'read write',
            'redirect_uri': 'http://example.it',
        })
        url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'),
                                  qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        # check form is in context and form params are valid
        self.assertIn("form", response.context)

        form = response.context["form"]
        self.assertEqual(form['redirect_uri'].value(), "http://example.it")
        self.assertEqual(form['state'].value(), "random_state_string")
        self.assertEqual(form['scope'].value(), "read write")
        self.assertEqual(form['client_id'].value(), self.application.client_id)
Exemplo n.º 5
0
    def test_access_token_and_id_token_skip_authorization_completely(self):
        """
        If application.skip_authorization = True, should skip the authorization page.
        """
        self.client.login(username="******", password="******")
        self.application.skip_authorization = True
        self.application.save()

        query_string = urlencode({
            "client_id": self.application.client_id,
            "response_type": "id_token token",
            "state": "random_state_string",
            "nonce": "random_nonce_string",
            "scope": "openid",
            "redirect_uri": "http://example.org",
        })

        url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"),
                                  qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)
        self.assertIn("http://example.org#", response["Location"])
        self.assertIn("access_token=", response["Location"])
        self.assertIn("id_token=", response["Location"])
        self.assertIn("state=random_state_string", response["Location"])

        uri_query = urlparse(response["Location"]).fragment
        uri_query_params = dict(
            parse_qs(uri_query, keep_blank_values=True, strict_parsing=True))
        id_token = uri_query_params["id_token"][0]
        jwt_token = jwt.JWT(key=self.key, jwt=id_token)
        claims = json.loads(jwt_token.claims)
        self.assertIn("nonce", claims)
        self.assertIn("at_hash", claims)
    def test_revoke_token_with_wrong_hint(self):
        """
        From the revocation rfc, `Section 4.1.2`_ :

        If the server is unable to locate the token using the given hint,
        it MUST extend its search across all of its supported token types
        .. _`Section 4.1.2`: http://tools.ietf.org/html/draft-ietf-oauth-revocation-11#section-4.1.2
        """
        tok = AccessToken.objects.create(user=self.test_user,
                                         token="1234567890",
                                         application=self.application,
                                         expires=timezone.now() +
                                         datetime.timedelta(days=1),
                                         scope="read write")

        query_string = urlencode({
            "client_id": self.application.client_id,
            "client_secret": self.application.client_secret,
            "token": tok.token,
            "token_type_hint": "refresh_token"
        })
        url = "{url}?{qs}".format(url=reverse("oauth2_provider:revoke-token"),
                                  qs=query_string)
        response = self.client.post(url)
        self.assertEqual(response.status_code, 200)
        self.assertFalse(AccessToken.objects.filter(id=tok.id).exists())
 def test_pre_auth_approval_prompt(self):
     """
     TODO
     """
     tok = AccessToken.objects.create(user=self.test_user,
                                      token='1234567890',
                                      application=self.application,
                                      expires=timezone.now() +
                                      datetime.timedelta(days=1),
                                      scope='read write')
     self.client.login(username="******", password="******")
     query_string = urlencode({
         'client_id': self.application.client_id,
         'response_type': 'code',
         'state': 'random_state_string',
         'scope': 'read write',
         'redirect_uri': 'http://example.it',
         'approval_prompt': 'auto',
     })
     url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'),
                               qs=query_string)
     response = self.client.get(url)
     self.assertEqual(response.status_code, 302)
     # user already authorized the application, but with different scopes: prompt them.
     tok.scope = 'read'
     tok.save()
     response = self.client.get(url)
     self.assertEqual(response.status_code, 200)
    def test_revoke_access_token_public(self):
        public_app = Application(
            name="Test Application",
            redirect_uris=
            "http://localhost http://example.com http://example.org",
            user=self.dev_user,
            client_type=Application.CLIENT_PUBLIC,
            authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
        )
        public_app.save()

        tok = AccessToken.objects.create(user=self.test_user,
                                         token="1234567890",
                                         application=public_app,
                                         expires=timezone.now() +
                                         datetime.timedelta(days=1),
                                         scope="read write")

        query_string = urlencode({
            "client_id": public_app.client_id,
            "token": tok.token,
        })

        url = "{url}?{qs}".format(url=reverse("oauth2_provider:revoke-token"),
                                  qs=query_string)
        response = self.client.post(url)
        self.assertEqual(response.status_code, 200)
    def test_pre_auth_default_scopes(self):
        """
        Test response for a valid client_id with response_type: code using default scopes
        """
        self.client.login(username="******", password="******")
        oauth2_settings._DEFAULT_SCOPES = ["read"]

        query_string = urlencode({
            "client_id": self.application.client_id,
            "response_type": "code",
            "state": "random_state_string",
            "redirect_uri": "http://example.org",
        })
        url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"),
                                  qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        # check form is in context and form params are valid
        self.assertIn("form", response.context)

        form = response.context["form"]
        self.assertEqual(form["redirect_uri"].value(), "http://example.org")
        self.assertEqual(form["state"].value(), "random_state_string")
        self.assertEqual(form["scope"].value(), "read")
        self.assertEqual(form["client_id"].value(), self.application.client_id)
        oauth2_settings._DEFAULT_SCOPES = ["read", "write"]
Exemplo n.º 10
0
    def get_context_data(self, **kwargs):

        kwargs['CLIENT_ID'] = urlencode(
            {'client_id': settings.DEFALUT_SENTRY_CLIENT_ID})
        kwargs['OAUTH_SERVER'] = settings.OAUTH_SERVER
        context = super(HomeView, self).get_context_data(**kwargs)
        return context
Exemplo n.º 11
0
 def form_valid(self, form):
     qs = urlencode({
         'client_id': form.cleaned_data['client_id'],
         'response_type': 'code',
         'state': 'random_state_string',
     })
     self.authorization_link = "{url}?{qs}".format(url=form.cleaned_data['authorization_url'], qs=qs)
     return super(ConsumerView, self).form_valid(form)
Exemplo n.º 12
0
 def form_valid(self, form):
     qs = urlencode({
         'client_id': form.cleaned_data['client_id'],
         'response_type': 'code',
         'state': 'random_state_string',
     })
     self.authorization_link = "{url}?{qs}".format(
         url=form.cleaned_data['authorization_url'], qs=qs)
     return super(ConsumerView, self).form_valid(form)
    def test_pre_auth_invalid_client(self):
        """
        Test error for an invalid client_id with response_type: code
        """
        self.client.login(username="******", password="******")

        query_string = urlencode({
            'client_id': 'fakeclientid',
            'response_type': 'code',
        })
        url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)
    def test_request_is_not_overwritten(self):
        self.client.login(username="******", password="******")
        query_string = urlencode({
            'client_id': self.application.client_id,
            'response_type': 'code',
            'state': 'random_state_string',
            'scope': 'read write',
            'redirect_uri': 'http://example.it',
        })
        url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        assert 'request' not in response.context_data
    def test_pre_auth_wrong_response_type(self):
        """
        Test error when passing a wrong response_type in query string
        """
        self.client.login(username="******", password="******")

        query_string = urlencode({
            'client_id': self.application.client_id,
            'response_type': 'WRONG',
        })
        url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)
        self.assertIn("error=unsupported_response_type", response['Location'])
    def test_request_is_not_overwritten(self):
        self.client.login(username="******", password="******")
        query_string = urlencode({
            "client_id": self.application.client_id,
            "response_type": "code",
            "state": "random_state_string",
            "scope": "read write",
            "redirect_uri": "http://example.org",
        })
        url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"),
                                  qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        assert "request" not in response.context_data
    def test_pre_auth_forbibben_redirect(self):
        """
        Test error when passing a forbidden redirect_uri in query string with response_type: code
        """
        self.client.login(username="******", password="******")

        query_string = urlencode({
            'client_id': self.application.client_id,
            'response_type': 'code',
            'redirect_uri': 'http://forbidden.it',
        })
        url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)
    def test_pre_auth_default_redirect(self):
        """
        Test for default redirect uri if omitted from query string with response_type: code
        """
        self.client.login(username="******", password="******")

        query_string = urlencode({
            'client_id': self.application.client_id,
            'response_type': 'code',
        })
        url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        form = response.context["form"]
        self.assertEqual(form['redirect_uri'].value(), "http://localhost")
Exemplo n.º 19
0
    def test_revoke_access_token_with_hint(self):
        """

        """
        tok = AccessToken.objects.create(user=self.test_user, token='1234567890',
                                         application=self.application,
                                         expires=timezone.now() + datetime.timedelta(days=1),
                                         scope='read write')
        query_string = urlencode({
            'client_id': self.application.client_id,
            'client_secret': self.application.client_secret,
            'token': tok.token,
            'token_type_hint': 'access_token'
        })
        url = "{url}?{qs}".format(url=reverse('oauth2_provider:revoke-token'), qs=query_string)
        response = self.client.post(url)
        self.assertEqual(response.status_code, 200)
        self.assertFalse(AccessToken.objects.filter(id=tok.id).exists())
 def test_revoke_access_token_with_invalid_hint(self):
     tok = AccessToken.objects.create(
         user=self.test_user, token="1234567890",
         application=self.application,
         expires=timezone.now() + datetime.timedelta(days=1),
         scope="read write"
     )
     # invalid hint should have no effect
     query_string = urlencode({
         "client_id": self.application.client_id,
         "client_secret": self.application.client_secret,
         "token": tok.token,
         "token_type_hint": "bad_hint"
     })
     url = "{url}?{qs}".format(url=reverse("oauth2_provider:revoke-token"), qs=query_string)
     response = self.client.post(url)
     self.assertEqual(response.status_code, 200)
     self.assertFalse(AccessToken.objects.filter(id=tok.id).exists())
    def test_skip_authorization_completely(self):
        """
        If application.skip_authorization = True, should skip the authorization page.
        """
        self.client.login(username="******", password="******")
        self.application.skip_authorization = True
        self.application.save()

        query_string = urlencode({
            'client_id': self.application.client_id,
            'response_type': 'code',
            'state': 'random_state_string',
            'scope': 'read write',
            'redirect_uri': 'http://example.it',
        })
        url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)
    def test_pre_auth_valid_client_default_scopes(self):
        """
        Test response for a valid client_id with response_type: token and default_scopes
        """
        self.client.login(username="******", password="******")
        query_string = urlencode({
            'client_id': self.application.client_id,
            'response_type': 'token',
            'state': 'random_state_string',
            'redirect_uri': 'http://example.it',
        })

        url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        self.assertIn("form", response.context)
        form = response.context["form"]
        self.assertEqual(form['scope'].value(), 'read')
Exemplo n.º 23
0
    def test_pre_auth_valid_client_default_scopes(self):
        """
        Test response for a valid client_id with response_type: token and default_scopes
        """
        self.client.login(username="******", password="******")
        query_string = urlencode({
            "client_id": self.application.client_id,
            "response_type": "token",
            "state": "random_state_string",
            "redirect_uri": "http://example.org",
        })

        url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"), qs=query_string)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        self.assertIn("form", response.context)
        form = response.context["form"]
        self.assertEqual(form["scope"].value(), "read")
    def test_pre_auth_invalid_client(self):
        """
        Test error for an invalid client_id with response_type: code
        """
        self.client.login(username="******", password="******")

        query_string = urlencode({
            "client_id": "fakeclientid",
            "response_type": "code",
        })
        url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"),
                                  qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(
            response.context_data["url"],
            "?error=invalid_request&error_description=Invalid+client_id+parameter+value."
        )
    def test_skip_authorization_completely(self):
        """
        If application.skip_authorization = True, should skip the authorization page.
        """
        self.client.login(username="******", password="******")
        self.application.skip_authorization = True
        self.application.save()

        query_string = urlencode({
            "client_id": self.application.client_id,
            "response_type": "code",
            "state": "random_state_string",
            "scope": "read write",
            "redirect_uri": "http://example.org",
        })
        url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"),
                                  qs=query_string)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)
Exemplo n.º 26
0
    def get_context_data(self, **kwargs):
        sentry_instance = None
        try:
            user = UserDetail.objects.get(name=self.request.user.username)
            organization = Organization.objects.get(organization_name=user.org_name)
            sentry_instance = SentryInstance.objects.get(sentry_instance_name=organization.sentry_instance)
            print sentry_instance
        except ObjectDoesNotExist:
            pass

        if settings.DEBUG:
            client_id = "ZvwRr6t?WkzuHO5htOkCjti-FHL=Ri5DsA!;6qWX"
        else:
            client_id = sentry_instance.client_id
        kwargs['CLIENT_ID'] = urlencode({'client_id': client_id})

        kwargs['OAUTH_SERVER'] = "http://localhost:8000"

        context = super(HomeView, self).get_context_data(**kwargs)
        return context
    def test_pre_auth_approval_prompt_default_override(self):
        """
        TODO
        """
        oauth2_settings.REQUEST_APPROVAL_PROMPT = 'auto'

        AccessToken.objects.create(user=self.test_user, token='1234567890',
                                   application=self.application,
                                   expires=timezone.now() + datetime.timedelta(days=1),
                                   scope='read write')
        self.client.login(username="******", password="******")
        query_string = urlencode({
            'client_id': self.application.client_id,
            'response_type': 'code',
            'state': 'random_state_string',
            'scope': 'read write',
            'redirect_uri': 'http://example.it',
        })
        url = "{url}?{qs}".format(url=reverse('oauth2_provider:authorize'), qs=query_string)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)
    def test_pre_auth_approval_prompt_default_override(self):
        oauth2_settings.REQUEST_APPROVAL_PROMPT = "auto"

        AccessToken.objects.create(user=self.test_user,
                                   token="1234567890",
                                   application=self.application,
                                   expires=timezone.now() +
                                   datetime.timedelta(days=1),
                                   scope="read write")
        self.client.login(username="******", password="******")
        query_string = urlencode({
            "client_id": self.application.client_id,
            "response_type": "code",
            "state": "random_state_string",
            "scope": "read write",
            "redirect_uri": "http://example.org",
        })
        url = "{url}?{qs}".format(url=reverse("oauth2_provider:authorize"),
                                  qs=query_string)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 302)
 def test_revoke_refresh_token(self):
     tok = AccessToken.objects.create(
         user=self.test_user, token="1234567890",
         application=self.application,
         expires=timezone.now() + datetime.timedelta(days=1),
         scope="read write"
     )
     rtok = RefreshToken.objects.create(
         user=self.test_user, token="999999999",
         application=self.application, access_token=tok
     )
     query_string = urlencode({
         "client_id": self.application.client_id,
         "client_secret": self.application.client_secret,
         "token": rtok.token,
     })
     url = "{url}?{qs}".format(url=reverse("oauth2_provider:revoke-token"), qs=query_string)
     response = self.client.post(url)
     self.assertEqual(response.status_code, 200)
     self.assertFalse(RefreshToken.objects.filter(id=rtok.id).exists())
     self.assertFalse(AccessToken.objects.filter(id=rtok.access_token.id).exists())
Exemplo n.º 30
0
    def get_context_data(self, **kwargs):

        kwargs['CLIENT_ID'] = urlencode({'client_id': settings.DEFALUT_SENTRY_CLIENT_ID})
        kwargs['OAUTH_SERVER'] = settings.OAUTH_SERVER
        context = super(HomeView, self).get_context_data(**kwargs)
        return context
Exemplo n.º 31
0
 def get_success_url(self):
     url = super(ConsumerView, self).get_success_url()
     return '{url}?{qs}'.format(
         url=url,
         qs=urlencode({'authorization_link': self.authorization_link}))
Exemplo n.º 32
0
 def get_success_url(self):
     url = super(ConsumerView, self).get_success_url()
     return '{url}?{qs}'.format(url=url, qs=urlencode({'authorization_link': self.authorization_link}))