def generate_access_tokens(request: WSGIRequest, user: User): # generate bearer token bearer_token = BearerToken(OAuth2Validator()) request.scopes = ["read", "write"] request.state = None request.extra_credentials = None request.grant_type = 'client_credentials' request.client = Application.objects.get( client_id=settings.SOCIAL_AUTH_CLIENT_ID, client_secret=settings.SOCIAL_AUTH_CLIENT_SECRET) token = bearer_token.create_token(request) # generate JWT issuer = settings.JWT_ISSUER payload_enricher = getattr(settings, 'JWT_PAYLOAD_ENRICHER', None) extra_data = {'username': user.username} if user else {} jwt_request = HttpRequest() jwt_request.POST = extra_data if payload_enricher: fn = import_string(payload_enricher) extra_data.update(fn(jwt_request)) payload = generate_payload(issuer, token['expires_in'], **extra_data) token['access_token_jwt'] = encode_jwt(payload) return token
def _get_access_token_jwt(self, request, content): extra_data = {} issuer = settings.JWT_ISSUER payload_enricher = getattr(settings, 'JWT_PAYLOAD_ENRICHER', None) if payload_enricher: fn = import_string(payload_enricher) extra_data = fn(request) extra_data["access_token"] = content["access_token"] if 'scope' in content: extra_data['scope'] = content['scope'] id_attribute = getattr(settings, 'JWT_ID_ATTRIBUTE', None) if id_attribute: token = get_access_token_model().objects.get( token=content['access_token'] ) id_value = getattr(token.user, id_attribute, None) if not id_value: raise MissingIdAttribute() extra_data[id_attribute] = str(id_value) payload = generate_payload(issuer, content['expires_in'], **extra_data) token = encode_jwt(payload) return token
def _create_headers(user: CoreUser, organization_uuid: string) -> dict: extra_data = { "organization_uuid": organization_uuid, "core_user_uuid": user.core_user_uuid, "username": user.username, } payload = generate_payload(settings.JWT_ISSUER, expires_in=600, **extra_data) token = encode_jwt(payload) return {"Authorization": "JWT " + token, "Content-Type": "application/json"}
def test_generate_payload_no_extra_data(self, mock_datetime): now = datetime.utcnow() mock_datetime.utcnow.return_value = now issuer, expires_in = self._get_payload_args() expiration = now + timedelta(seconds=expires_in) self.assertEqual(utils.generate_payload(issuer, expires_in), { 'iss': issuer, 'exp': expiration, 'iat': now, })
def test_generate_payload_with_extra_data(self, mock_datetime): now = datetime.utcnow() mock_datetime.utcnow.return_value = now issuer, expires_in = self._get_payload_args() expiration = now + timedelta(seconds=expires_in) extra_data = { 'usr': '******', 'org': 'some_org', 'sub': 'subject', } self.assertEqual( utils.generate_payload(issuer, expires_in, **extra_data), { 'iss': issuer, 'exp': expiration, 'iat': now, 'sub': 'subject', 'usr': '******', 'org': 'some_org', })