Skip to main content

Documentation Index

Fetch the complete documentation index at: https://samsara-showcase.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

This recipe shows the core OAuth 2.0 flow for Marketplace Apps: redirect users to Samsara, exchange the authorization code for credentials, use the access token, refresh expired credentials, and revoke credentials.
# Python 3.6 or newer required.
import base64
import os
import secrets
import time
from threading import Lock

import flask
import requests

app = flask.Flask(__name__)
app.secret_key = secrets.token_bytes(16)

client_id = os.environ["SAMSARA_CLIENT_ID"]
client_secret = os.environ["SAMSARA_CLIENT_SECRET"]
redirect_uri = "http://localhost:5000/auth/samsara/callback"

refresh_token_mutex = Lock()


def encoded_credentials():
    app_credentials = client_id + ":" + client_secret
    return str(base64.b64encode(app_credentials.encode("utf-8")), "utf-8")


def refresh_access_token():
    response = requests.request(
        "POST",
        "https://api.samsara.com/oauth2/token",
        headers={
            "Authorization": "Basic " + encoded_credentials(),
            "Content-Type": "application/x-www-form-urlencoded",
        },
        data={
            "refresh_token": flask.session["credentials"]["refresh_token"],
            "grant_type": "refresh_token",
        },
    )

    flask.session["credentials"] = response.json()
    flask.session["credentials"]["expires_at"] = (
        time.time() + flask.session["credentials"]["expires_in"]
    )


def get_access_token():
    while refresh_token_mutex.locked():
        time.sleep(0.5)

    if time.time() > flask.session["credentials"]["expires_at"]:
        refresh_token_mutex.acquire()
        refresh_access_token()
        refresh_token_mutex.release()

    return flask.session["credentials"]["access_token"]


@app.route("/authorize")
def authorize():
    flask.session["state"] = secrets.token_urlsafe(8)
    return flask.redirect(
        "https://api.samsara.com/oauth2/authorize?"
        + "client_id="
        + client_id
        + "&state="
        + flask.session["state"]
        + "&response_type=code"
        + "&redirect_uri="
        + redirect_uri
    )


@app.route("/auth/samsara/callback")
def oauth2callback():
    state = flask.request.args.get("state", "")
    if flask.session["state"] != state:
        return flask.redirect(flask.url_for("authorize"))

    authorization_code = flask.request.args.get("code", "")
    response = requests.request(
        "POST",
        "https://api.samsara.com/oauth2/token",
        headers={
            "Authorization": "Basic " + encoded_credentials(),
            "Content-Type": "application/x-www-form-urlencoded",
        },
        data={
            "code": authorization_code,
            "grant_type": "authorization_code",
            "redirect_uri": redirect_uri,
        },
    )

    flask.session["credentials"] = response.json()
    flask.session["credentials"]["expires_at"] = time.time() + response.json()["expires_in"]
    return flask.redirect(flask.url_for("list_vehicles"))


@app.route("/list_vehicles")
def list_vehicles():
    response = requests.request(
        "GET",
        "https://api.samsara.com/fleet/vehicles",
        headers={"Authorization": "Bearer " + get_access_token()},
    )
    return response.json()

How it works

1

Import dependencies

Use your language’s web framework, HTTP client, session storage, cryptography, and Base64 utilities.
2

Load app credentials

Creating a new OAuth 2.0 app gives you an App ID and App Secret. Store them securely, such as in environment variables.
3

Request app authorization

Redirect users to https://api.samsara.com/oauth2/authorize with client_id, state, response_type=code, and redirect_uri.
4

Define the OAuth callback

Samsara redirects users back to your app’s configured redirect URI after they authorize the app.
5

Verify state

Compare the returned state with the value stored in the user’s session to help prevent CSRF attacks.
6

Exchange the authorization code

Send a POST request to https://api.samsara.com/oauth2/token with Basic authentication and grant_type=authorization_code.
7

Save credentials

Store access_token, refresh_token, and an expiration timestamp. Use durable storage in production.
8

Use the access token

Include the access token in API requests using the Authorization: Bearer TOKEN header.
9

Refresh expired credentials

If the access token expires, send a POST request to /oauth2/token with grant_type=refresh_token.
10

Revoke credentials

Send a POST request to /oauth2/revoke to revoke a refresh token and clear stored credentials.
See OAuth 2.0 for the full OAuth guide.