Cropwise
powered by syngenta

Cropwise Authentication Guide

Introduction

This guide will help you authenticate with the Cropwise API using OAuth 2.0. As a Cropwise developer, you have been provided with:

  • Email: Your Cropwise user account email
  • Client ID: Your application's unique identifier
  • Client Secret: Your application's secret key (keep this secure!)
  • Redirect URI (optional): Your application's callback URL (e.g., http://localhost:3000/callback)

Base URL

All API requests should be made to:

https://api.cropwise.com

Available Authentication Methods

Cropwise supports two OAuth 2.0 grant types:

  1. Client Credentials Grant (Recommended for most applications - server-to-server communication)
  2. Authorization Code Grant (For web applications requiring user interaction)

This method is used for server-to-server authentication where no user interaction is required. This is ideal for backend services that need to access Cropwise APIs on behalf of your application (not a specific user). This is the recommended method for most integrations.

Flow Diagram

Step 1: Request Access Token

Make a POST request to obtain an access token:

Request:

POST /oauth/token HTTP/1.1
Host: api.cropwise.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic {BASE64_ENCODED_CREDENTIALS}

grant_type=client_credentials&scope=read

Authorization Header: The BASE64_ENCODED_CREDENTIALS is your Client ID and Client Secret encoded in Base64:

Base64("{CLIENT_ID}:{CLIENT_SECRET}")

Example using curl:

curl -X POST https://api.cropwise.com/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -H "Authorization: Basic $(echo -n 'YOUR_CLIENT_ID:YOUR_CLIENT_SECRET' | base64)" \
  -d "grant_type=client_credentials" \
  -d "scope=read"

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "read"
}

Step 2: Use Access Token

Include the access token in your API requests:

curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  https://api.cropwise.com/v2/orgs

Method 2: Authorization Code Grant

This method is recommended for web applications where users interact with a browser and you need to act on behalf of a specific user.

Flow Diagram

Step 1: Direct User to Authorization Endpoint

Redirect your user to the following URL:

https://api.cropwise.com/oauth/authorize?client_id={YOUR_CLIENT_ID}&redirect_uri={YOUR_REDIRECT_URI}&response_type=code

Parameters:

  • client_id: Your application's client ID
  • redirect_uri: Your registered redirect URI (must match exactly)
  • response_type: Must be code

Example:

https://api.cropwise.com/oauth/authorize?client_id=abc123&redirect_uri=http://localhost:3000/callback&response_type=code

Step 2: User Signs In

The user will be redirected to the Cropwise sign-in page where they'll enter their email and password.

Step 3: Receive Authorization Code

After successful authentication, Cropwise will redirect the user back to your redirect_uri with an authorization code:

http://localhost:3000/callback?code={AUTHORIZATION_CODE}

Step 4: Exchange Code for Access Token

Make a POST request to exchange the authorization code for an access token:

Request:

POST /oauth/token HTTP/1.1
Host: api.cropwise.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic {BASE64_ENCODED_CREDENTIALS}

grant_type=authorization_code&code={AUTHORIZATION_CODE}&redirect_uri={YOUR_REDIRECT_URI}

Authorization Header: The BASE64_ENCODED_CREDENTIALS is your Client ID and Client Secret encoded in Base64:

Base64("{CLIENT_ID}:{CLIENT_SECRET}")

Example using curl:

curl -X POST https://api.cropwise.com/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -H "Authorization: Basic $(echo -n 'YOUR_CLIENT_ID:YOUR_CLIENT_SECRET' | base64)" \
  -d "grant_type=authorization_code" \
  -d "code=AUTHORIZATION_CODE_FROM_STEP_3" \
  -d "redirect_uri=http://localhost:3000/callback"

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "read write"
}

Step 5: Use Access Token

Include the access token in your API requests:

curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  https://api.cropwise.com/v2/orgs

Quick Start Decision Tree


Code Examples

Python Example (Client Credentials Grant)

import requests
import base64

# Your credentials
CLIENT_ID = "your_client_id"
CLIENT_SECRET = "your_client_secret"

# Encode credentials
credentials = base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()

# Request access token
token_response = requests.post(
    "https://api.cropwise.com/oauth/token",
    headers={
        "Authorization": f"Basic {credentials}",
        "Content-Type": "application/x-www-form-urlencoded"
    },
    data={
        "grant_type": "client_credentials",
        "scope": "read"
    }
)

token_data = token_response.json()
access_token = token_data['access_token']
print(f"Access Token: {access_token}")

# Use access token for API requests
api_response = requests.get(
    "https://api.cropwise.com/v2/orgs",
    headers={"Authorization": f"Bearer {access_token}"}
)

print(f"Organizations: {api_response.json()}")

JavaScript/Node.js Example (Client Credentials Grant)

const axios = require('axios');

const CLIENT_ID = 'your_client_id';
const CLIENT_SECRET = 'your_client_secret';

async function authenticate() {
  // Encode credentials
  const credentials = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');

  try {
    // Request access token
    const response = await axios.post(
      'https://api.cropwise.com/oauth/token',
      new URLSearchParams({
        grant_type: 'client_credentials',
        scope: 'read'
      }),
      {
        headers: {
          'Authorization': `Basic ${credentials}`,
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    );

    const { access_token } = response.data;
    console.log('Access Token:', access_token);

    // Use access token for API requests
    const apiResponse = await axios.get(
      'https://api.cropwise.com/v2/orgs',
      {
        headers: {
          'Authorization': `Bearer ${access_token}`
        }
      }
    );

    console.log('Organizations:', apiResponse.data);
    return apiResponse.data;
  } catch (error) {
    console.error('Authentication failed:', error.response?.data || error.message);
  }
}

authenticate();

Python Example (Authorization Code Grant)

import requests
import base64
from urllib.parse import urlencode, parse_qs, urlparse

# Your credentials
CLIENT_ID = "your_client_id"
CLIENT_SECRET = "your_client_secret"
REDIRECT_URI = "http://localhost:3000/callback"

# Step 1: Generate authorization URL
auth_params = {
    'client_id': CLIENT_ID,
    'redirect_uri': REDIRECT_URI,
    'response_type': 'code'
}
auth_url = f"https://api.cropwise.com/oauth/authorize?{urlencode(auth_params)}"
print(f"Visit this URL to authorize: {auth_url}")

# Step 2: After user authorizes, extract code from callback URL
callback_url = input("Enter the full callback URL: ")
code = parse_qs(urlparse(callback_url).query)['code'][0]

# Step 3: Exchange code for access token
credentials = base64.b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()
token_response = requests.post(
    "https://api.cropwise.com/oauth/token",
    headers={
        "Authorization": f"Basic {credentials}",
        "Content-Type": "application/x-www-form-urlencoded"
    },
    data={
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": REDIRECT_URI
    }
)

token_data = token_response.json()
access_token = token_data['access_token']
print(f"Access Token: {access_token}")

# Step 4: Use access token for API requests
api_response = requests.get(
    "https://api.cropwise.com/v2/orgs",
    headers={"Authorization": f"Bearer {access_token}"}
)

print(f"Organizations: {api_response.json()}")

Security Best Practices

  1. Never expose your Client Secret: Keep it secure and never commit it to version control or expose it in client-side code.

  2. Use HTTPS: Always use HTTPS in production. The examples use http://localhost for development only.

  3. Store tokens securely: Store access tokens and refresh tokens securely (e.g., encrypted storage, environment variables).

  4. Handle token expiration: Access tokens expire. Implement proper token refresh logic or re-authentication.

  5. Validate redirect URIs: Ensure your redirect URI matches exactly what was registered with Cropwise (only applicable for Authorization Code Grant).

  6. Use Client Credentials Grant for most integrations: It's the recommended method for server-to-server communication. Use Authorization Code Grant only when you need to act on behalf of specific users.


Troubleshooting

Common Error Responses

400 Bad Request - Invalid credentials

{
  "error": "invalid_grant",
  "error_description": "Invalid client credentials"
}
  • Check that your Client ID and Client Secret are correct
  • Verify that your client is properly registered

401 Unauthorized

  • Check that your Client ID and Client Secret are correct
  • Verify the Authorization header is properly formatted

Redirect URI mismatch

  • Ensure the redirect URI in your request exactly matches the one registered with Cropwise
  • Check for trailing slashes and protocol (http vs https)

Additional Resources