SDKS

Python SDK

The WorkOS Python SDK provides your Python applications convenient access to the WorkOS Audit Trail and SSO APIs.

Installation

To get started, you can install the WorkOS package via PyPi with:

Terminal

file_copy
pip install workos

Alternatively, you can also install from source:

Terminal

file_copy
git clone git@github.com:workos-inc/workos-python.git && cd workos-python && python setup.py install

View the source on GitHub.


Configuration

To use the SDK you must first provide your API key and Project ID from the Developer Dashboard.

You can set the API key and Project ID after importing the module, before your application starts:

Python

file_copy
import workos

workos.api_key = "{secretKey}"
workos.project_id = "{projectId}"

The audit_trail Module

The audit_trail module provides convenience methods for publishing application events to WorkOS.

workos.audit_trail.create_event(event, idempotency_key=None)

workos.audit_trail.create_event accepts two arguments:

  • event (dictionary) — an event object containing descriptive attributes that detail your application's event.
  • idempotency_key (string, optional, defaults to None) — a unique value which the server uses to recognize successive retries of the same request and safely retry requests without creating the same event more than once.

For example, publishing a non-idempotent event:

Python

file_copy
event = {
  "group": "example.com",
  "location": "65.215.8.114",
  "action": "user.login_succeeded",
  "action_type": "R",
  "actor_name": "annie.easley@{foo-corp.com}",
  "actor_id": "user_01DEQWZNQT8Y47HDPSJKQS1J3F",
  "target_name": "annie.easley@{foo-corp.com}",
  "target_id": "user_01DEQWZNQT8Y47HDPSJKQS1J3F",
  "occurred_at": "2020-07-14T16:05:22.387Z",
  "metadata": {
    "source": "Email",
  }
}

workos.audit_trail.create_event(event)

Results in WorkOS logging the following event:

JSON

file_copy
{
  "id": "evt_04DKH0F9DXZJ312A8G0CKRJ648Y",
  "group": "example.com",
  "location": "65.215.8.114",
  "action": "user.login_succeeded",
  "action_type": "R",
  "actor_name": "annie.easley@{foo-corp.com}",
  "actor_id": "user_01DEQWZNQT8Y47HDPSJKQS1J3F",
  "target_name": "annie.easley@{foo-corp.com}",
  "target_id": "user_01DEQWZNQT8Y47HDPSJKQS1J3F",
  "occurred_at": "2020-07-14T16:05:22.387Z",
  "metadata": {
    "source": "Email",
  }
}

For details about the specific use of each event attribute, as well as more information about using idempotency keys and metadata, refer to the API Reference.

The sso Module

The sso Module provides convenience methods for authenticating a Single Sign-on user via WorkOS. WorkOS SSO follows the OAuth 2.0 specification.

First, you'll direct your users to an authorization_url. They will sign in to their account with their Identity Provider, and be redirected to a callback URL that you set in your WorkOS Dashboard. The user will be redirected with a code URL parameter, which you can then exchange for a WorkOSProfile using the workos.sso.get_profile method.

See our Python SSO example app for a complete example.

workos.sso.get_authorization_url(domain, redirect_uri, state=None)

Generate an authorization URL to intitiate the WorkOS OAuth2 workflow.

workos.sso.get_authorization_url accepts four arguments:

  • domain (string) — the authenticating user's company domain, without protocol (ex. example.com)
  • redirectURI (string) — a callback URL where your application redirects the user-agent after an authorization code is granted (ex. workos.dev/callback)
  • provider (ConnectionType) — optional parameter that specifies the type of Connection to authenticate with. If used, a user of any domain can be authenticated. Only GoogleOAuth is currently supported. Most commonly used for "Signup with Google" buttons.
  • state (optional, string) — an optional encoded string used to manage state across authorization transactions (ex. { next_page: '/docs'})

This method will return an OAuth2 query string of the form:

https://api.workos.com/sso/authorize?response_type=code&domain=${domain}&client_id=${projectID}&redirect_uri=${redirectURI}&state=${state}

For example, when used in a Flask app:

app.py

file_copy
DOMAIN = '{foo-corp.com}'
REDIRECT_URI = '{redirectURI}'

@app.route('/auth')
def auth():
    authorization_url = client.sso.get_authorization_url(
        DOMAIN,
        REDIRECT_URI,
        state=''
    )

    return redirect(authorization_url)

The user would be redirected to:

https://api.workos.com/sso/authorize?response_type=code&domain=foo-corp.com&client_id={projectID}&redirect_uri=http://localhost:4567/callback

WorkOS takes over from here, sending the user to authenticate with their IDP, and on successful login, returns the user to your callback URL with a code parameter. You'll use workos.sso.get_profile to exchange the code for a WorkOSProfile.

workos.sso.get_profile(code)

Fetch a WorkOSProfile for an authorized user.

workos.sso.get_profile accepts one argument:

code (string) — an opaque string provided by the authorization server; will be exchanged for an Access Token when the user's profile is sent

This method will return an instance of a WorkOSProfile object with the following attributes:

Python

file_copy
{
  "id": "prof_01DRA1XNSJDZ19A31F183ECQW5",
  "email": "demo@{foo-corp.com}",
  "first_name": "WorkOS",
  "last_name": "Demo",
  "connection_type": "OktaSAML",
  "idp_id": "00u1klkowm8EGah2H357",
}

The Flask app can be extended to use this method:

app.py

file_copy
DOMAIN = '{foo-corp.com}'
REDIRECT_URI = '{redirectURI}'

@app.route('/auth')
def auth():
    authorization_url = client.sso.get_authorization_url(
        DOMAIN,
        REDIRECT_URI,
        state=''
    )

    return redirect(authorization_url)

@app.route('/auth/callback')
def auth_callback():
    code = request.args.get('code')
    profile = client.sso.get_profile(code)

    return profile.to_dict()

Given the WorkOSProfile, you can now sign the user in according to your own authentication setup.