YipiiYipii IoT Docs

Authentication

OAuth2 authentication guide for the Yipii IoT API

Share

The Yipii IoT API uses OAuth2 with the Client Credentials flow for server-to-server authentication. This guide covers how to authenticate and manage access tokens.

OAuth2 Client Credentials Flow

The Client Credentials flow is designed for machine-to-machine authentication where your application directly accesses the API without user interaction.

Flow Overview

  1. Your application sends client credentials to the token endpoint
  2. The API validates credentials and returns an access token
  3. Use the access token in the Authorization header for API requests
  4. Refresh the token before it expires

Obtaining Tokens

Token Endpoint

POST https://api.yipii.io/oauth/token

Request Parameters

ParameterTypeRequiredDescription
grant_typestringYesMust be client_credentials
client_idstringYesYour OAuth2 client ID
client_secretstringYesYour OAuth2 client secret
scopestringNoSpace-separated list of scopes (optional)

Code Examples

cURL

curl -X POST "https://api.yipii.io/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"

JavaScript (Node.js)

const axios = require('axios');
 
async function getAccessToken() {
  const response = await axios.post('https://api.yipii.io/oauth/token',
    new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: process.env.YIPII_CLIENT_ID,
      client_secret: process.env.YIPII_CLIENT_SECRET,
    }),
    {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    }
  );
 
  return response.data.access_token;
}
 
// Usage
const token = await getAccessToken();
console.log('Access token:', token);

JavaScript (Fetch API)

async function getAccessToken() {
  const response = await fetch('https://api.yipii.io/oauth/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: 'YOUR_CLIENT_ID',
      client_secret: 'YOUR_CLIENT_SECRET',
    }),
  });
 
  const data = await response.json();
  return data.access_token;
}

PHP

<?php
 
function getAccessToken(): string
{
    $ch = curl_init('https://api.yipii.io/oauth/token');
 
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded',
        ],
        CURLOPT_POSTFIELDS => http_build_query([
            'grant_type' => 'client_credentials',
            'client_id' => getenv('YIPII_CLIENT_ID'),
            'client_secret' => getenv('YIPII_CLIENT_SECRET'),
        ]),
    ]);
 
    $response = curl_exec($ch);
    curl_close($ch);
 
    $data = json_decode($response, true);
    return $data['access_token'];
}
 
// Usage
$token = getAccessToken();
echo "Access token: " . $token;

Python

import requests
import os
 
def get_access_token():
    response = requests.post(
        'https://api.yipii.io/oauth/token',
        data={
            'grant_type': 'client_credentials',
            'client_id': os.environ['YIPII_CLIENT_ID'],
            'client_secret': os.environ['YIPII_CLIENT_SECRET'],
        }
    )
 
    response.raise_for_status()
    return response.json()['access_token']
 
# Usage
token = get_access_token()
print(f'Access token: {token}')

Token Response

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
  "token_type": "Bearer",
  "expires_in": 31536000
}
FieldDescription
access_tokenThe JWT token to use for API requests
token_typeAlways Bearer
expires_inToken lifetime in seconds (typically 1 year)

Using Access Tokens

Include the access token in the Authorization header of all API requests:

curl -X GET "https://api.yipii.io/api/{account_key}/asset" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Accept: application/json"

JavaScript Example

async function fetchAssets(accountKey, accessToken) {
  const response = await fetch(
    `https://api.yipii.io/api/${accountKey}/asset`,
    {
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Accept': 'application/json',
      },
    }
  );
 
  return response.json();
}

PHP Example

function fetchAssets(string $accountKey, string $accessToken): array
{
    $ch = curl_init("https://api.yipii.io/api/{$accountKey}/asset");
 
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer {$accessToken}",
            'Accept: application/json',
        ],
    ]);
 
    $response = curl_exec($ch);
    curl_close($ch);
 
    return json_decode($response, true);
}

Account Key

The account key is a unique identifier for your account, used in all API endpoints:

https://api.yipii.io/api/{account_key}/resource

Finding Your Account Key

  1. From the Dashboard URL: Your account key appears in the URL when logged in:

    https://iot.yipii.io/a/{ACCOUNT_KEY}/dashboard
  2. From the User Endpoint: Call the user profile endpoint:

    curl -X GET "https://api.yipii.io/api/v1/user" \
      -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

    Response includes your accounts:

    {
      "data": {
        "id": 1,
        "name": "John Doe",
        "accounts": [
          {
            "id": 123,
            "key": "acme-fleet",
            "name": "ACME Fleet"
          }
        ]
      }
    }

Token Management

Token Expiration

Access tokens have a long lifetime (typically 1 year), but you should:

  1. Store tokens securely - Never expose tokens in client-side code or logs
  2. Handle 401 responses - Refresh the token if you receive an unauthorized error
  3. Rotate periodically - Consider refreshing tokens proactively for security

Handling Expired Tokens

class YipiiClient {
  constructor(clientId, clientSecret, accountKey) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.accountKey = accountKey;
    this.accessToken = null;
  }
 
  async getToken() {
    if (!this.accessToken) {
      this.accessToken = await this.fetchNewToken();
    }
    return this.accessToken;
  }
 
  async fetchNewToken() {
    const response = await fetch('https://api.yipii.io/oauth/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        grant_type: 'client_credentials',
        client_id: this.clientId,
        client_secret: this.clientSecret,
      }),
    });
 
    const data = await response.json();
    return data.access_token;
  }
 
  async request(endpoint, options = {}) {
    const token = await this.getToken();
 
    const response = await fetch(
      `https://api.yipii.io/api/${this.accountKey}${endpoint}`,
      {
        ...options,
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json',
          ...options.headers,
        },
      }
    );
 
    // Handle expired token
    if (response.status === 401) {
      this.accessToken = null;
      return this.request(endpoint, options);
    }
 
    return response.json();
  }
}
 
// Usage
const client = new YipiiClient(
  process.env.YIPII_CLIENT_ID,
  process.env.YIPII_CLIENT_SECRET,
  'acme-fleet'
);
 
const assets = await client.request('/asset');

Security Best Practices

Never expose your Client Secret in client-side code, public repositories, or logs.

Do

  • Store credentials in environment variables or a secure vault
  • Use HTTPS for all API requests
  • Rotate credentials periodically
  • Implement proper error handling for authentication failures

Don't

  • Hardcode credentials in source code
  • Log access tokens or credentials
  • Share credentials between environments
  • Use the same credentials for development and production

Environment Variable Example

# .env file (never commit this!)
YIPII_CLIENT_ID=your_client_id
YIPII_CLIENT_SECRET=your_client_secret
YIPII_ACCOUNT_KEY=your_account_key
// Load from environment
const client = new YipiiClient(
  process.env.YIPII_CLIENT_ID,
  process.env.YIPII_CLIENT_SECRET,
  process.env.YIPII_ACCOUNT_KEY
);

Error Responses

Invalid Credentials

{
  "error": "invalid_client",
  "error_description": "Client authentication failed",
  "message": "Client authentication failed"
}

Expired Token

{
  "message": "Unauthenticated."
}

HTTP Status: 401 Unauthorized

Next Steps

Was this page helpful?

Authentication | Yipii IoT Docs