Giter Site home page Giter Site logo

okta-sdk-python's People

Contributors

alimcmaster1 avatar bjr-okta avatar bretterer avatar bryanapellanes-okta avatar coreysmithring avatar corylevine avatar drewcarmichael-okta avatar gabrielsroka avatar glebinsky avatar jmelberg-okta avatar joelfranusic-okta avatar justinabrokwah-okta avatar keeshendriks avatar lboyette-okta avatar lebarondecharlus avatar mattcumminswmg avatar nbarbettini avatar nicolastrres avatar omidraha avatar ph-ngn avatar rdegges avatar scheblein avatar serhiibuniak-okta avatar shiqiyang-okta avatar tbelote-okta avatar vijetmahabaleshwar-okta avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

okta-sdk-python's Issues

AttributeError when retrieving paginated logs

Hello I'm running into an error when using pagination with client.gets_logs().

Here is my code:

#!/usr/bin/env python3.7

from okta.client import Client as OktaClient
from datetime import datetime, timedelta
import asyncio

# Okta config
okta_config = {
    'orgUrl': 'https://company.okta.com',
    'token': 'redacted'
}


async def get_okta_logs():
    logs = []
    client = OktaClient(okta_config)
    params = {
        'filter': 'eventType eq "user.account.lock"',
        'since': (datetime.now() - timedelta(7)).isoformat()[:-3] + 'Z',
        'until': datetime.now().isoformat()[:-3] + 'Z',
        'limit': '1'
    }

    events, response, error = await client.get_logs(query_params=params)
    for event in events:
        logs.append(event)
    if response.has_next():  # Returns True
        events, error = await response.next()
        for event in events:
            logs.append(event)

    if error:
        print(f'Okta API Error: {error}')

    print(logs)

The error I receive:

Traceback (most recent call last):
  File "okta_logs.py", line 40, in <module>
    asyncio.run(get_okta_logs())
  File "/usr/local/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "okta_logs.py", line 30, in get_okta_logs
    events, error = await response.next()
  File "/usr/local/lib/python3.8/site-packages/okta/api_response.py", line 129, in next
    result.append(self._type(item))
  File "/usr/local/lib/python3.8/site-packages/okta/models/log_event.py", line 70, in __init__
    self.authentication_context = log_authentication_context.LogAuthenticationContext(
  File "/usr/local/lib/python3.8/site-packages/okta/models/log_authentication_context.py", line 48, in __init__
    config["authenticationProvider"].upper()
AttributeError: 'NoneType' object has no attribute 'upper'

My code has no issues receiving the first page, however when I use response.next() I keep seeing the attribute error.

pip install is broken

Installing okta python sdk via pip, only fetches the files in the root folder (AppInstanceClient.py, AuthClient.py, etc.), the folders "framework" and "models" are not download, hence the okta python sdk won't work.

sudo pip install okta

python okta_python_test.py
Traceback (most recent call last):
  File "okta_python", line 2, in <module>
    from okta import AppInstanceClient
  File "/Library/Python/2.7/site-packages/okta/AppInstanceClient.py", line 1, in <module>
    from okta.framework.ApiClient import ApiClient
ImportError: No module named framework.ApiClient

This is how the python package looks after using sudo pip install okta:

ls -l /Library/Python/2.7/site-packages/okta
total 176
-rw-r--r--  1 root  wheel  1971 Sep  6 18:52 AppInstanceClient.py
-rw-r--r--  1 root  wheel  3241 Sep  6 18:52 AppInstanceClient.pyc
-rw-r--r--  1 root  wheel  6098 Sep  6 18:52 AuthClient.py
-rw-r--r--  1 root  wheel  6274 Sep  6 18:52 AuthClient.pyc
-rw-r--r--  1 root  wheel   759 Sep  6 18:52 EventsClient.py
-rw-r--r--  1 root  wheel  1448 Sep  6 18:52 EventsClient.pyc
-rw-r--r--  1 root  wheel  1016 Sep  6 18:52 FactorsAdminClient.py
-rw-r--r--  1 root  wheel  1836 Sep  6 18:52 FactorsAdminClient.pyc
-rw-r--r--  1 root  wheel  4285 Sep  6 18:52 FactorsClient.py
-rw-r--r--  1 root  wheel  5645 Sep  6 18:52 FactorsClient.pyc
-rw-r--r--  1 root  wheel  1716 Sep  6 18:52 SessionsClient.py
-rw-r--r--  1 root  wheel  2924 Sep  6 18:52 SessionsClient.pyc
-rw-r--r--  1 root  wheel  1533 Sep  6 18:52 UserGroupsClient.py
-rw-r--r--  1 root  wheel  2585 Sep  6 18:52 UserGroupsClient.pyc
-rw-r--r--  1 root  wheel  2843 Sep  6 18:52 UsersClient.py
-rw-r--r--  1 root  wheel  3997 Sep  6 18:52 UsersClient.pyc
-rw-r--r--  1 root  wheel    44 Sep  6 18:52 __init__.py
-rw-r--r--  1 root  wheel   168 Sep  6 18:52 __init__.pyc

If I manually download the folders "framework" and "models" and add them to "/Library/Python/2.7/site-packages/okta" everything works.

bonus: have a look at the pull requests and either accept them or send them back.

hello world?

can we update the README with a hello world? for example, i'm trying to get this to work, but it's not working

from okta.client import Client as OktaClient
import asyncio

async def main():
    client = OktaClient()
    users, resp, err = await client.list_users()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Using get_logs shows an HTTP 405 error

Hello, I'm testing the SDK for our services and I keep getting an HTTP 405 error when trying to retrieve our system logs.

EVENTS: None
RESPONSE: <okta.api_response.OktaAPIResponse object at 0x7f2623dd2d30>
ERROR: {'message': "HTTP 405 {'errorCode': 'E0000022', 'errorSummary': 'HTTP 405 Method Not Allowed', 'errorId': '9cbbc6a3-3e53-488b-9229-e2a5c784a5f7'}"}

Here is my code:

from okta.client import Client as OktaClient
import asyncio
from datetime import datetime, timedelta

config = {
    'orgUrl': 'https://somecompany.okta.com',
    'token': 'redacted'
}

async def main():
    client = OktaClient(config)
    params = {
        'filter': 'eventType eq "user.session.start" and outcome.reason eq "UNKNOWN_USER"',
        'since': (datetime.now() - timedelta(7)).isoformat()[:-3] + 'Z',
        'until': datetime.now().isoformat()[:-3] + 'Z'
    }
    events, response, error = await client.get_logs(query_params=params)
    print(f"EVENTS: {events}")
    print(f"RESPONSE: {response}")
    print(f"ERROR: {error}")

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Tried checking if it was my parameters so I tried removing 'filter' or using only 'since' for the past day. I even tried with no parameters and I'm still getting a 405 error code.

Issue while initializing an AuthClient instance

The following error is seen while initializing an AuthClient object.

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/shetty/work/django/pyenv/src/okta/okta/AuthClient.py", line 8, in __init__
    ApiClient.__init__(self, base_url + '/api/v1/authn', api_token)
  File "/Users/shetty/work/django/pyenv/src/okta/okta/framework/ApiClient.py", line 12, in __init__
    self.base_url = kwargs['base_url'] or args[0]
KeyError: 'base_url'```

HTTP delete requests returns `204 No Content` But keyword fail

It fails because the method try to return Utils.deserialize when response.text is empty --> "No JSON object could be decoded"

So either

  1. Return None on all 204 expected keywords
    Or
  2. At Utils.deserialize add one more if case:
    Util.py line:19
        if from_data:
            json_dump = {}
        elif isinstance(from_data, six.text_type) or isinstance(from_data, six.string_types):
            json_dump = json.loads(from_data)
        else:
            json_dump = from_data

Or whatever you think is fit here

Request body not well formed during verify

Hello,

I'm trying to prompt the user for push auth via the SDK for testing purposes. According to the documentation this is a valid request :

factor_response = factorClient.verify_factor(user.id, factor.id)

This results in the following call"

curl -i -s -k  -X $'POST' \
    -H $'User-Agent: python-requests/2.18.4' -H $'Content-Type: application/json' -H $'Authorization: SSWS XXXXXX' \
    --data-binary $'{\"activationToken\":null,\"answer\":null,\"passCode\":null,\"nextPassCode\":null}' \
    $'https://example.oktapreview.com/api/v1/users/XXXXX/factors/XXXXX/verify'

Which returns an error The request body was not well-formed.

Fiddling around w/ Postman, submitting no body at all gives the desired results.

SDK does not officially support update of user profile custom attributes

Due to the way the UserProfile model is built, it has a set of properties that it uses in its dict when request data is serialized or response data is deserialized.

The set of properties is static which means that if you set a user profile attribute that is not part of the standard Okta attributes, it vanishes when you make your requests, and likewise when looking up a user and serializing their user profile, the user profile appears to not have any of the custom attributes that were added.

In order to work around this, it's possible to do something like this:

user_profile = UserProfile(...).as_dict()
user_profile[{custom_attribute}] = value

When providing the user profile to things like create/update user, user_profile can be passed instead of the actual UserProfile model object itself.

The ability to add custom attributes in a supported way would be nice to have when working with the SDK.

asyncio should not put under requirements.txt

Hi community,
I am now using python 3.7+ with pip-compile.
And I will get error with asyncio if I installed it from pip.
From the doc in asyncio,

asyncio requires Python 3.3 or later! The asyncio module is part of the Python standard library since Python 3.4.

And also,

This version is only relevant for Python 3.3, which does not include asyncio in its stdlib.

So, my suggestion here is to remove the asyncio and release the okta package with 3.3+ only.
Thank you!

How can I paginate throuhgh all users? (alpha 1.0.0 release)

The readme shows an example of paginating to get the next page but that does appear to return the "resp" object so I can then recursively run the .has_next and get all of the values. In my case I am referring to users but they use they same object for the OktaApiResponse if im not mistaken. The example shown in the readme shows

if resp.has_next:
    next_users, err = await resp.next()

but how can I continue to iterate through all the responses to get all users for example.

Thanks

SamlApplicationSettingsApplication/missing `app` key

I'm currently working on a DR solution for Okta that allows us to backup our configuration in serialised format to be later restored.

To do this, we're relying primarily on the ability to instantiate the appropriate OktaObject type using the config dict, and then calling the relevant create_x method.

Most of the other application types (e.g BookmarkApplication) have a corresponding class to which it delegates a settings key (e.g BookmarkApplicationSettings), which in turn delegates an app key to another corresponding class (e.g BookmarkApplicationSettingsApplication. It appears that this convention is missing for SAML application types, and as a result we are missing crucial information needed to be able to restore a SAML application.

An example partial response from Okta API containing this information:

{'name': 'yourcausesaml', 'label': 'YourCause',
....
'settings': {'app': {'envType': 'yourcause', 'subDomain': 'foo'}
...
}
SamlApplicationSettings(config=saml_api_response['settings']).app
{}

Would be nice to have a sample code as a use case to pull custom okta user attributes

I am looking for an example code that would be a replacement for the code below:
oidc = OpenIDConnect(app)
okta_client = UsersClient("{{ OKTA_ORG_URL }}", "{{ OKTA_AUTH_TOKEN }}")

@app.before_request
def before_request():
if oidc.user_loggedin:
g.user = okta_client.get_user(oidc.user_getfield("sub"))
else:
g.user = None

I want to be able to access custom attributes thru g.user

Thanks

The request body is not well-formed during User update

When reading a user from the API, altering some of the details on the profile, and then updating details via the API I see the following error

okta.framework.OktaError.OktaError: The request body was not well-formed`

Code:

try:
    # Okta returns [] if not found
    okta_users = users_client.get_users(
        query=supplier_details['email']
    )
except OktaError as okta_error:
    raise OktaCommsError(str(okta_error))

okta_user = okta_users[0]
okta_user.profile.email = supplier_details['email']
okta_user.profile.firstName = supplier_details['first_name']
okta_user.profile.lastName = supplier_details['last_name']
okta_user.profile.login = supplier_details['login']
okta_user.profile.displayName = supplier_details['display_name']
okta_user.profile.primaryPhone = supplier_details['primary_phone']
okta_user.profile.city = supplier_details['city']

try:
    users_client.update_user(okta_user)
except OktaError as okta_error:  # Error raises here
    # Something failed in the update
    raise OktaCommsError(str(okta_error))

Is there something I'm missing here?

NameError: name 'User' is not defined

When I try to run the example code in the quickstart.rst, I get this error:

Traceback (most recent call last):
  File "create_client.py", line 6, in <module>
    new_user = User(login='[email protected]',
NameError: name 'User' is not defined

Here is the example code that I'm trying to execute:

from okta import UsersClient
# http://developer.okta.com/docs/api/getting_started/getting_a_token.html
usersClient = UsersClient('https://dev-212920-admin.okta.com',
                              'xxxxxxxxsxxxxxxxxxxxxxxxxxxx')
                              
new_user = User(login='[email protected]',
                    email='[email protected]',
                    firstName='Saml',
                    lastName='Jackson')
user = usersClient.create_user(new_user, activate=False)

user = usersClient.get_user('[email protected]')
usersClient.activate_user(user.id)

users = usersClient.get_paged_users()
while True:
    for user in users.result:
        print u"First Name: {}".format(user.profile.firstName)
        print u"Last Name:  {}".format(user.profile.lastName)
        print u"Login:      {}".format(user.profile.login)
        print u"User ID:    {}\n".format(user.id)
    if not users.is_last_page():
            # Keep on fetching pages of users until the last page
        users = usersClient.get_paged_users(url=users.next_url)
    else:
        break

pip install broken?

root:~# pip install okta
Collecting okta
  Could not find a version that satisfies the requirement okta (from versions: )
No matching distribution found for okta

root:~# pip --version
pip 7.0.3 from /usr/local/lib/python2.7/dist-packages (python 2.7)

HTTP/400 Errors if the API Token contains a newline

Ran into an issue where I am decrypting an [AWS encrypted] Okta API token that ended with a newline.
Normally, you would not include a newline on the token, but because of the tools I was using it inserted an extra \n. It was non-obvious as the inputs to my app were encrypted.
Some deeper urllib3 debug logging helped

When requests module constructed the POST, it contained the SSWS token value with the extra \n, which is not a valid HTTP request.
The Apache front end webserver at okta rejects the malformed request, and returns some standard apache HTML error page.
The okta-sdk library never expects HTML payloads in the response, and throws a JSON parsing exception.

(The request is not reaching the Okta application servers where JSON can be returned in the response. It is being dropped as a HTTP/400 by the Apache service fronting the application servers).

For defensiveness, I am suggesting the module handles non-HTML responses gracefully, and/or strips any whitespace/newlines from the user specified token.

I have since reencrypted the token without the extra newline, and everything works, but in case someone else has this problem the module could handle this edge case.

Line 20 in utils.py throws exception

When calling UserClient.delete_user(uid), oktasdk-python/okta/framework/Utils.py line 20 throws an exception (ValueError: No JSON object could be decoded). Presumably, whatever the okta API is returning is either not JSON, or is being improperly parsed.
What's that about?

Assign roles to User

Hi everyone, I am looking for a way to assign roles to a user. Specifically I am trying to make a user administrator of an application. Is there some way to do that using the oktasdk at this moment?

New user is not assigned to an application

When I follow the doc:

from okta import UsersClient
# http://developer.okta.com/docs/api/getting_started/getting_a_token.html
usersClient = UsersClient('https://example.oktapreview.com/',
                          '01a2B3Cd4E5fGHiJ6K7l89mNOPQRsT0uVwXYZA1BCd')

new_user = User(login='[email protected]',
                email='[email protected]',
                firstName='Saml',
                lastName='Jackson')
user = usersClient.create_user(new_user, activate=False)

The user is created, but not assigned to an application. I have two applications after running the migration process from Stormpath. Is this the problem? That it does not know which application to assign the new user to? How do I resolve this?

Security status and support

Hi, is there any chance for Okta to support this library again? I managed to get this working on my Flask application and it's working well.

Is it secure enough for corporate use?

Thanks!

sample to create a new App

I am trying to create a new app through the create_app_instance method but without success.

The configuration of the AppInstance is not obvious.

app_client = AppInstanceClient("...","...")
app = AppInstance()
app.label = "my-new-app"
app.signOnMode = "OPENID_CONNECT"
app_client.create_app_instance(app)

gets me a
okta.framework.OktaError.OktaError: Internal Server Error

If I also set credentials, visibility, settings and accessibility (by just using values from an existing app I get a
okta.framework.OktaError.OktaError: Api validation failed: mediated

Could you post some simple sample to create an App ?

Expose request "headers" to provide additional functionality

Expose the ability to provide additional "headers" (such as "X-Forwarded-For") for factor verification (example method = "verify_factor")

Some API calls have the ability to send additional headers.

I may consider forking this for a pull request.

'RADIUS_FOR_CISCO_ASA' & 'AWS_FEDERATED_LOGIN' not recognized as valid ApplicationSignOnModes

When getting a list of all applications via: apps, resp, err = await client.list_applications() it fails with the message: 'RADIUS_FOR_CISCO_ASA' is not a valid ApplicationSignOnMode & 'AWS_FEDERATED_LOGIN' is not a valid ApplicationSignOnMode respectively. It seems that those two application sign on modes need to be added to the application_sign_on_mode.py file. Also, equivalent models need to be created for each. Once those models are created, they need to be added to the OKTA_APP_SIGN_ON_TO_MODEL variable in the constants.py file.

get_group_users returns only 1000 elements

groups_client = UserGroupsClient(base_url=settings.OKTA_BASE_URL, api_token=settings.OKTA_API_TOKEN)
users = groups_client.get_group_users(gid)

users contains only first 1000 items.
After debug:
response = ApiClient.get_path(self, '/{0}/users'.format(gid))
'next' in response.links returns True

url = 'https://xxxx.okta.com/api/v1/groups/xxxxxxx/users'
params = None

Based on the description should return 10,000.
https://developer.okta.com/docs/api/resources/groups/#list-group-members
In any case, the case of large groups is not taken into account.

Also checked with postman. The same behavior.
I also suspect that other API methods may have a similar problem.

User model lacks some fields

The user/userProfile models are lacking some important attributes. In particular, 'employeeNumber' is missing. The PowerShell scripting does have some of these other attributes. However, what would be even better is if we could utilize other fields, particularly those which we may have added on a custom basis.

Is this repository actively maintained?

Hi all,

Just wondering if this repo is actively maintained or whether I should just be using the REST API directly with something like requests. I ask because I see there are a few unanswered issues and PRs over the past few months.

list_applications returning KeyError

I'm trying to list all the applications in an okta instance and getting the following result from the coroutine.

(None, <okta.api_response.OktaAPIResponse object at 0x7f2e4490dd50>, KeyError('office365'))

import asyncio
import os
from okta.client import Client

OKTA_URL = os.environ.get("OKTA_URL")
OKTA_SSWS = os.environ.get("OKTA_SSWS")

client = Client({"orgUrl": OKTA_URL, "token": OKTA_SSWS})
loop = asyncio.get_event_loop()
x = loop.run_until_complete(client.list_applications())
print(x)

countryCode not included in UserProfile

countryCode should really be included as an argument of the UserProfile. Really, all the default attributes should be, but this is specifically necessary for provisioning licenses in O365 (or so my O365 admin tells me).

It has to be added in the following places:

  • As an attribute of the UserProfile class
  • As a key/value pair (value str) in the types dictionary which is an attribute of the UserProfile class
  • As an element of the profile_attrs list in the init method of the User class

I was able to make the above changes and successfully create users with the countryCode value as a kwarg when creating a User object.

Using list_group_users returns an HTTP 405 error

Hi all,

I'm testing out list_group_users for a new service, and it's returning a 405 error on the call:

{'message': 'Okta HTTP 405 E0000022 The endpoint does not support the provided HTTP method'}

The code I'm using is as follows, shortened for relevance:

import asyncio
from okta.client import Client as OktaClient

okta_group = redacted

okta_config = {
    'orgUrl': redacted,
    'token': redacted
}

async def okta_group_members():
    employees = []
    params = {
        'limit': 200
    }
    try:
        users, response, error = await okta_client.list_group_users(
            groupId=okta_group, query_params=params
        )
        while True:
            if users is not None:
                for user in users:
                    user_sanitized = {
                        'first_name': user.profile.first_name,
                        'last_name': user.profile.last_name,
                        'user_id': user.id,
                        'email': user.profile.email,
                        'status': user.status
                    }
                    employees.append(user_sanitized)
                if response.has_next():
                    users, error = await response.next()
                else:
                    break
            elif error is not None:
                logger.error(f'Okta API Error: {error}')
    except Exception as e:
        logger.exception(f'Error retrieving users from the group: {e}')
    return employees

async def main():
    okta_member_list = await okta_group_members()
    print(okta_member_list)

if __name__ == '__main__':
    asyncio.run(main())

I'm able to make this call without issues using requests, though.

State token is set to 'None' on successful authentication

When I make a call to the authenticate() method, the returned AuthResult object has the stateToken field set to 'None'. The authentication status was deemed to be successful and the user being authenticated is active in the Okta's people directory. Please see code snippet below:

>>> res = auth_client.authenticate("[email protected]", "Password123")
>>> res.stateToken
>>> res.status
u'SUCCESS'
>>> print res.stateToken
None
>>>

Client doesn't work on Python3.5 (likely other versions as well)

Forgive me, I'm new to python. However, I've had a friend also look at this to verify and he was able to reproduce on py3.2. Looks like the pathing is relative in https://github.com/okta/oktasdk-python/blob/master/okta/__init__.py. So, when python tries to import it's looking for (in my case i'm using a virtual env) site-packages/AppInstanceClient, instead of okta/AppInstanceClient.

My guess is that the imports should look like okta.AppInstanceClient inside init.py. This appears to mirror what I've seen in various other modules that work properly. I've tried to address the issue that way and did get past the problem below, but then ran into other pathing issues within the module.

(venv) xxx:/tmp$ pip install okta
Collecting okta
  Using cached okta-0.0.3-py2.py3-none-any.whl
Collecting six>=1.9.0 (from okta)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting python-dateutil>=2.4.2 (from okta)
  Using cached python_dateutil-2.4.2-py2.py3-none-any.whl
Collecting requests>=2.5.3 (from okta)
  Using cached requests-2.9.1-py2.py3-none-any.whl
Installing collected packages: six, python-dateutil, requests, okta
Successfully installed okta-0.0.3 python-dateutil-2.4.2 requests-2.9.1 six-1.10.0
(venv) xxx:/tmp$ vim foo.py
(venv) xxx:/tmp$ python3 foo.py
Traceback (most recent call last):
  File "foo.py", line 1, in <module>
    from okta import AuthClient
  File "/private/tmp/venv/lib/python3.5/site-packages/okta/__init__.py", line 12, in <module>
    from AppInstanceClient import AppInstanceClient
ImportError: No module named 'AppInstanceClient'
(venv) xxx:/tmp$ cat foo.py
from okta import AuthClient

Issue with authenticate() method

Following is my code snippet:

def authenticate(self, username, password):
        self.logger.debug("Attempting to authenticate user: %s" % username)
        auth_client = AuthClient(base_url=self.base_url, api_token=self.api_key)
        auth_result = auth_client.authenticate(username=username, password=password)
        self.logger.debug("Authentication result: username: %s status: %s" % (username, auth_result.status))
        return auth_result.status

I get the following error while attempting to authenticate a user that has been successfully created on the Okta server.

>>> okta_backend.authenticate(username, password)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/shetty/work/authentication/models.py", line 136, in authenticate
    return auth_engine.authenticate(username, password)
  File "/Users/shetty/work/authentication/auth_okta.py", line 35, in authenticate
    auth_result = auth_client.authenticate(username=username, password=password)
  File "/Users/shetty/pyenv/src/okta/okta/AuthClient.py", line 41, in authenticate
    response = ApiClient.post_path(self, '/', request, params=params)
  File "/Users/shetty/pyenv/src/okta/okta/framework/ApiClient.py", line 88, in post_path
    return self.post(self.base_url + url_path, data, params)
  File "/Users/shetty/pyenv/src/okta/okta/framework/ApiClient.py", line 67, in post
    if self.__check_response(resp, attempts):
  File "/Users/shetty/pyenv/src/okta/okta/framework/ApiClient.py", line 102, in __check_response
    raise OktaError(json.loads(resp.text))
OktaError: Authentication failed

What is missing

Here is my script, almost identical to the sample script in the README

from okta.client import Client as OktaClient
import asyncio
import os

config = {
    'orgUrl': os.getenv("OKTA_DOMAIN"),
    'token': os.getenv("OKTA_API_TOKEN")
}

client = OktaClient(config)

async def main():
    users, resp, err = await client.list_users()
    print(len(users))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Here is the error message

Traceback (most recent call last):
  File "okta-query.py", line 1, in <module>
    from okta.client import Client as OktaClient
  File "/Users/user/.python_3_envs/work_3.6/lib/python3.6/site-packages/okta/client.py", line 20, in <module>
    from okta.config.config_setter import ConfigSetter
  File "/Users/user/.python_3_envs/work_3.6/lib/python3.6/site-packages/okta/config/config_setter.py", line 4, in <module>
    from okta.constants import _GLOBAL_YAML_PATH, _LOCAL_YAML_PATH
  File "/Users/user/.python_3_envs/work_3.6/lib/python3.6/site-packages/okta/constants.py", line 2, in <module>
    import okta.models as models
  File "/Users/user/.python_3_envs/work_3.6/lib/python3.6/site-packages/okta/models/__init__.py", line 21, in <module>
    import okta.models.activate_factor_request as activate_factor_request
AttributeError: module 'okta' has no attribute 'models'

I'm using Python 3.6.8 and the okta library is 1.0.2 (most recent). Am I missing a library or setup step? Thanks.

No new release since Oct 2015

There has not been a new release since the initial release in Oct 2015. Is the expectation that we need to clone the source code regularly or can we expect to have released versions in the future?

Pipenv Won't Install Version 1.0.0 of Okta

When trying to run pipenv install okta to install version 1.0.0 on Python 3.8 I get:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 807, in <module>
    main()
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 802, in main
    _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write,
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 785, in _main
    resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages)
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 746, in resolve_packages
    results, resolver = resolve(
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 728, in resolve
    return resolve_deps(
  File "/usr/local/lib/python3.8/site-packages/pipenv/utils.py", line 1378, in resolve_deps
    results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(
  File "/usr/local/lib/python3.8/site-packages/pipenv/utils.py", line 1095, in actually_resolve_deps
    resolver.resolve_constraints()
  File "/usr/local/lib/python3.8/site-packages/pipenv/utils.py", line 847, in resolve_constraints
    marker = marker_from_specifier(candidate.requires_python)
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 719, in marker_from_specifier
    for marker_segment in cleanup_pyspecs(spec):
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 288, in cleanup_pyspecs
    for op_and_version_type, versions in _group_by_op(tuple(specs)):
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 203, in _group_by_op
    specs = [_get_specs(x) for x in list(specs)]
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 203, in <listcomp>
    specs = [_get_specs(x) for x in list(specs)]
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 187, in _get_specs
    for spec in set(specset):
TypeError: 'LegacySpecifier' object is not iterable

Running it with -v points to an issue when it's attempting to generate the hashes for Okta:

Generating hashes:
  flask-pyoidc
  cffi
  pluggy
  pyasn1-modules
  pyasn1
  ecdsa
  jsonschema
  attrs
  future
  flatdict
  httplib2
  flask-restful-swagger-2
  webargs
  aniso8601
  pytest-recording
  flask-swagger-ui
  pyparsing
  certifi
  iniconfig
  pycryptodome
  oic
  pyfakefs
  urllib3
  flake8
  oauth2client
  multidict
  flask
  requests
  importlib-resources
  py-healthcheck
  pycodestyle
  flask-smorest
  pytest-asyncio
  pycparser
  pyrsistent
  safrs
  packaging
  vcrpy
  pymysql
  mccabe
  pytest-mock
  toml
  mako
  markupsafe
  pytest
  click
  pydash
  rsa
  pytz
  itsdangerous
  wrapt
  beaker
  flask-cors
  pyjwt
  simplejson
  defusedxml
  py
  xmltodict
  chardet
  flask-oidc
  flask-caching
  cryptography
  pyflakes
  idna
  typing-extensions
  flask-restful
  mistune
  werkzeug
  pyjwkest
  marshmallow
  aiohttp
  apispec
  six
  sqlalchemy
  pyyaml
  jinja2
  asyncio
  pycryptodomex
  async-timeout
  flasgger
  pymongo
  flask-sqlalchemy
  okta
  python-jose
  inflect
  yarl
  aenum
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 807, in <module>
    main()
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 802, in main
    _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write,
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 785, in _main
    resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages)
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 746, in resolve_packages
    results, resolver = resolve(
  File "/usr/local/lib/python3.8/site-packages/pipenv/resolver.py", line 728, in resolve
    return resolve_deps(
  File "/usr/local/lib/python3.8/site-packages/pipenv/utils.py", line 1378, in resolve_deps
    results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(
  File "/usr/local/lib/python3.8/site-packages/pipenv/utils.py", line 1095, in actually_resolve_deps
    resolver.resolve_constraints()
  File "/usr/local/lib/python3.8/site-packages/pipenv/utils.py", line 847, in resolve_constraints
    marker = marker_from_specifier(candidate.requires_python)
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 719, in marker_from_specifier
    for marker_segment in cleanup_pyspecs(spec):
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 288, in cleanup_pyspecs
    for op_and_version_type, versions in _group_by_op(tuple(specs)):
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 203, in _group_by_op
    specs = [_get_specs(x) for x in list(specs)]
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 203, in <listcomp>
    specs = [_get_specs(x) for x in list(specs)]
  File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/requirementslib/models/markers.py", line 187, in _get_specs
    for spec in set(specset):
TypeError: 'LegacySpecifier' object is not iterable

I am able to install version 0.0.4 without issues

Where is the new location of okta.framework.OktaError?

First off congrats on the 1.0.0 release! :-)

We have some code that uses OktaError and expects to find it at from okta.framework.OktaError import OktaError as in your 0.0.4 release, but it looks like things have changed since 1.0.0. What is the new exception type that I should use now, and does it still have the same error codes as before? E.g. "E0000006".

Here's the error message that I get:

cartography/intel/okta/__init__.py:3: in <module>
    from okta.framework.OktaError import OktaError
E   ModuleNotFoundError: No module named 'okta.framework'

And here's the line: https://github.com/lyft/cartography/blob/2f3016bfe1cc4543c0d526fa067d166a70116b26/cartography/intel/okta/__init__.py#L3

And here's our failing CI build: https://travis-ci.org/github/lyft/cartography/builds/737221215#L529

Possibly related to

Appreciate the help!

Rate limit date format isn't handled properly and prevents hitting backoff code

in okta.request_executor, it seems that when you get rate limited, the server passes back a Date header that contains a string containing a date/time with an unexpected format.

It seems that string is formatted in a way that the okta.util.convert_date_time_to_seconds doesn't expect and throws an exception.

if attempts < max_retries and (error or check_429):
      date_time = headers.get("Date", "")
      if date_time:
          date_time = convert_date_time_to_seconds(date_time)

It results in this (incomplete) stack trace:

Traceback (most recent call last):
   File "/usr/local/lib/python3.6/dist-packages/okta/resource_clients/application_client.py", line 1536, in assign_user_to_application
    .execute(request, AppUser)
  File "/usr/local/lib/python3.6/dist-packages/okta/request_executor.py", line 138, in execute
    _, response, response_body, error = await self.fire_request(request)
  File "/usr/local/lib/python3.6/dist-packages/okta/request_executor.py", line 176, in fire_request
    self.fire_request_helper(request, 0, time.time())
  File "/usr/local/lib/python3.6/dist-packages/okta/request_executor.py", line 229, in fire_request_helper
    date_time = convert_date_time_to_seconds(date_time)
  File "/usr/local/lib/python3.6/dist-packages/okta/utils.py", line 53, in convert_date_time_to_seconds
    DATETIME_FORMAT)
  File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.6/_strptime.py", line 362, in _strptime
    (data_string, format))
ValueError: time data 'Fri, 15 Jan 2021 05:53:21 GMT' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

I suggest standardizing this internally (ideally using ISO-8601 datetime format)

Full user profile

It seems like the user profile only sets a subset of the profile fields.

Is there a way to get the full profile?

asyncio conflict with python 3.8?

After including the okta sdk in my django project I got the following error:

Traceback (most recent call last):
  File "./manage.py", line 19, in <module>
    from configurations.management import execute_from_command_line
  File "/home/appuser/.local/lib/python3.8/site-packages/configurations/__init__.py", line 1, in <module>
    from .base import Configuration  # noqa
  File "/home/appuser/.local/lib/python3.8/site-packages/configurations/base.py", line 5, in <module>
    from django.conf import global_settings
  File "/home/appuser/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 19, in <module>
    from django.core.validators import URLValidator
  File "/home/appuser/.local/lib/python3.8/site-packages/django/core/validators.py", line 8, in <module>
    from django.utils.encoding import punycode
  File "/home/appuser/.local/lib/python3.8/site-packages/django/utils/encoding.py", line 8, in <module>
    from django.utils.deprecation import RemovedInDjango40Warning
  File "/home/appuser/.local/lib/python3.8/site-packages/django/utils/deprecation.py", line 1, in <module>
    import asyncio
  File "/home/appuser/.local/lib/python3.8/site-packages/asyncio/__init__.py", line 21, in <module>
    from .base_events import *
  File "/home/appuser/.local/lib/python3.8/site-packages/asyncio/base_events.py", line 296
    future = tasks.async(future, loop=self)
                   ^
SyntaxError: invalid syntax

After some googling I think it's because the asyncio package is in conflict with what's already included in python core 3.8. Has anybody else run into the same problem?

Looks like asyncio should no longer be needed for python version beyond 3.3.
https://pypi.org/project/asyncio/

is this here in order to support python versions even lower than 3.3?

Can't get values for existing custom attributes

When using the Okta User API (/api/v1/users/${userId}) with requests or Postman, I'm able to retrieve all attributes, including existing custom attributes.

When using the SDK I only get a predefined list of attributes from the UserProfile class. The README mentions how to modify UserProfile and set new values for a custom attribute. However, I can't figure out a way to retrieve existing values for custom attributes.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.