> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://es.megaport.ferndocs.com/es/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://es.megaport.ferndocs.com/es/_mcp/server.

# Generar Token de Acceso - Staging

POST https://api.megaport.com/oauth2/token
Content-Type: application/x-www-form-urlencoded

Genera un token de acceso con una clave de API en el entorno de Staging.

Después de haber creado una clave de API en el Portal, que consta de un ID de cliente y un secreto de cliente, puede generar un token de acceso (JWT) para la autorización de las API de Megaport. Los JWT son de corta duración y el tiempo de caducidad se establece cuando se crea la clave de API en el Portal (entre 5 minutos y 24 horas). La caducidad se puede ver en la respuesta de este punto final y se representa en segundos.

**Consejo:** Puede utilizar el sitio [https://jwt.io/](https://jwt.io/) para obtener más información y verificar el token de acceso. Copie el token de acceso (JWT) en el cuadro Codificado, mostrará información decodificada sobre el token. Por ejemplo, en los Datos de Payload, el valor `iat` indica cuándo se emitió el token (segundos desde la época Unix) y el valor `exp` indica cuándo caduca el token.

La URL de solicitud que necesita utilizar depende del entorno en el que está generando un token de acceso. En el entorno de **Staging**, se debe usar esta URL de solicitud:

* [https://auth-m2m-staging.megaport.com/oauth2/token](https://auth-m2m-staging.megaport.com/oauth2/token)

Para obtener más detalles sobre los entornos, consulte [Entornos](https://dev.megaport.com/#environments).

Proporcione valores para estos parámetros en la pestaña Autorización de la llamada:

* `Nombre de usuario` - El ID de cliente que copió al crear la clave de API.

* `Contraseña` - El secreto de cliente que copió al crear la clave de API.

**Nota:** Estos parámetros contienen datos sensibles. Si está trabajando en un entorno colaborativo, es posible que desee establecer el ID de cliente y el secreto de cliente como las variables \{\{apiKeyClientId}} y \{\{apiKeyClientSecret}} respectivamente.

En la pestaña Cuerpo, establezca el formato de codificación del cuerpo en `x-www-form-urlencoded` e introduzca una clave llamada *grant\_type* que se establezca con un valor de *client\_credentials*.

### **Uso del token de acceso**

Después de generar un token de acceso correctamente, verá estos valores en la respuesta:

* `access_token` - El token de acceso (JWT).

* `expires_in` - La caducidad del token, medida en segundos. Por ejemplo, si la caducidad se estableció en 24 horas en la clave de API, este valor sería 86400 (segundos). Si la caducidad se estableció en 5 minutos, entonces este valor sería 300.

* `token_type` - Bearer

Copie el token de acceso de la respuesta.

Puede crear una nueva variable para el token de acceso, asegurándose de copiar el token de acceso en el campo VALOR ACTUAL de la entrada de variable. Por ejemplo, llame a la nueva variable \{\{access\_token}}.

Para cada llamada de API que necesite enviar, en la pestaña Autorización, el Tipo debe establecerse en Token de portador y el Token debe establecerse en la variable de token de acceso \{\{access\_token}}.

Reference: https://es.megaport.ferndocs.com/es/api-reference/megaport-authentication-api-keys/generate-access-token-staging

## Authentication

- `Authorization` header (basic auth, required) — Basic authentication of the form `Basic <base64(username:password)>`.

## Servers

- `https://api.megaport.com` (Entorno de producción, default)
- `https://api-staging.megaport.com` (Entorno de pruebas (solo pruebas, se restablece cada 24 horas))

## Request

### Body (application/x-www-form-urlencoded)

This endpoint expects an object.

- `grant_type` (string, optional)

## Response

### 200

Generar Token de Acceso - Staging / Generar Token de Acceso - Staging / Generar Token de Acceso - Producción / Generar Token de Acceso - Producción

- `access_token` (string, optional)
- `expires_in` (double, optional)
- `token_type` (string, optional)

## Examples

### Generate Access Token - Production

**Request**

```json
{
  "grant_type": "client_credentials"
}
```

**Response**

```json
{
  "access_token": "eyJrbWQiOiIzZWhmUjhpbzd5R0pCYnBISWswbHU2d3V6ZzdtYWRcL1VWTjBTbm9XZVE3ND0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJsbjd0ZjR1Z2FtwTN1M29sNHU5amE2MjNwIiwidG9rZW5fdXNlIjoiYWNjZXNzIiwic2NvcGUiOiJodHRwczpcL1wvYXBpLXN0YWdpbmcubWVnYXBvcnQuY29tXC9jb21wYW55QWRtaW4iLCJhdXRoX3RpbWUiOjE3MDA2NDExMjcsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvxWlkcC5hcC1zb4V0aGVhc3QtMi5hbWF6b25hd3MuY29tXC9hcC1zb3V0aGVhc3QtMl9LbEh4TTlJUWoiLCJleHAiOjE3MDA3Mjc1MjcsImlhdCI6MTcwMDY0MTEyNywidmVyc2lvbiI6MiwianRpIjoiNzBkNGY1NzAtZWMwNS00NjM0LWFjOTktODJhY2MzNDE2ZThlIiwiY2xpZWg0X2lkIjoibG43dGY0dWdhbWUzdTNvbDR1OWphNjIzcCJ8.XIaEJBmkW3NnBZVrkpmR0u70UO_2MRONAhwtzDo7ql--R1ImWkUVA2ykEmi4eFMJXLzLewW4AQC-A9DC9EJAK2HwS7993ti-OMahfm1BI_0EqXPw-g_GpIulkUd3hTbu1_QifvfYzj3cxP5KxVULj76Xm2w1rKRw5pXdCcU4Y8n_qVlHy6sBYDjtzsKSfd6cBIRMHe-LnNWBLoHdS-tCPeDSMLqzq85MHKMCNt-KQGeuvTKU6PGaJSK1UXRHc5JivoJSeyuc-3vIXmq60fu0CwC0eVhOzkTWh6YUvBylDwYR50gYRfsMUIBbKGyQBP3sPQ2XQZrHMXodTLSKZG-khQ",
  "expires_in": 86400,
  "token_type": "Bearer"
}
```

**SDK Code**

```python Generate Access Token - Production
import requests

url = "https://api.megaport.com/oauth2/token"

payload = ""
headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

response = requests.post(url, data=payload, headers=headers, auth=("<username>", "<password>"))

print(response.json())
```

```javascript Generate Access Token - Production
const url = 'https://api.megaport.com/oauth2/token';
const credentials = btoa("<username>:<password>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams('')
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Generate Access Token - Production
package main

import (
	"fmt"
	"net/http"
	"io"
)

func main() {

	url := "https://api.megaport.com/oauth2/token"

	req, _ := http.NewRequest("POST", url, nil)

	req.SetBasicAuth("<username>", "<password>")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Generate Access Token - Production
require 'uri'
require 'net/http'

url = URI("https://api.megaport.com/oauth2/token")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request.basic_auth("<username>", "<password>")
request["Content-Type"] = 'application/x-www-form-urlencoded'

response = http.request(request)
puts response.read_body
```

```java Generate Access Token - Production
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.megaport.com/oauth2/token")
  .basicAuth("<username>", "<password>")
  .header("Content-Type", "application/x-www-form-urlencoded")
  .asString();
```

```php Generate Access Token - Production
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.megaport.com/oauth2/token', [
  'form_params' => null,
  'headers' => [
    'Content-Type' => 'application/x-www-form-urlencoded',
  ],
    'auth' => ['<username>', '<password>'],
]);

echo $response->getBody();
```

```csharp Generate Access Token - Production
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://api.megaport.com/oauth2/token");
client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
```

```swift Generate Access Token - Production
import Foundation

let credentials = Data("<username>:<password>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/x-www-form-urlencoded"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.megaport.com/oauth2/token")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### Generate Access Token - Staging

**Request**

```json
{
  "grant_type": "client_credentials"
}
```

**Response**

```json
{
  "access_token": "eyJrbWQiOiIzZWhmUjhpbzd5R0pCYnBISWswbHU2d3V6ZzdtYWRcL1VWTjBTbm9XZVE3ND0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJsbjd0ZjR1Z2FtwTN1M29sNHU5amE2MjNwIiwidG9rZW5fdXNlIjoiYWNjZXNzIiwic2NvcGUiOiJodHRwczpcL1wvYXBpLXN0YWdpbmcubWVnYXBvcnQuY29tXC9jb21wYW55QWRtaW4iLCJhdXRoX3RpbWUiOjE3MDA2NDExMjcsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvxWlkcC5hcC1zb4V0aGVhc3QtMi5hbWF6b25hd3MuY29tXC9hcC1zb3V0aGVhc3QtMl9LbEh4TTlJUWoiLCJleHAiOjE3MDA3Mjc1MjcsImlhdCI6MTcwMDY0MTEyNywidmVyc2lvbiI6MiwianRpIjoiNzBkNGY1NzAtZWMwNS00NjM0LWFjOTktODJhY2MzNDE2ZThlIiwiY2xpZWg0X2lkIjoibG43dGY0dWdhbWUzdTNvbDR1OWphNjIzcCJ8.XIaEJBmkW3NnBZVrkpmR0u70UO_2MRONAhwtzDo7ql--R1ImWkUVA2ykEmi4eFMJXLzLewW4AQC-A9DC9EJAK2HwS7993ti-OMahfm1BI_0EqXPw-g_GpIulkUd3hTbu1_QifvfYzj3cxP5KxVULj76Xm2w1rKRw5pXdCcU4Y8n_qVlHy6sBYDjtzsKSfd6cBIRMHe-LnNWBLoHdS-tCPeDSMLqzq85MHKMCNt-KQGeuvTKU6PGaJSK1UXRHc5JivoJSeyuc-3vIXmq60fu0CwC0eVhOzkTWh6YUvBylDwYR50gYRfsMUIBbKGyQBP3sPQ2XQZrHMXodTLSKZG-khQ",
  "expires_in": 86400,
  "token_type": "Bearer"
}
```

**SDK Code**

```python Generate Access Token - Staging
import requests

url = "https://api.megaport.com/oauth2/token"

payload = ""
headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

response = requests.post(url, data=payload, headers=headers, auth=("<username>", "<password>"))

print(response.json())
```

```javascript Generate Access Token - Staging
const url = 'https://api.megaport.com/oauth2/token';
const credentials = btoa("<username>:<password>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams('')
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Generate Access Token - Staging
package main

import (
	"fmt"
	"net/http"
	"io"
)

func main() {

	url := "https://api.megaport.com/oauth2/token"

	req, _ := http.NewRequest("POST", url, nil)

	req.SetBasicAuth("<username>", "<password>")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Generate Access Token - Staging
require 'uri'
require 'net/http'

url = URI("https://api.megaport.com/oauth2/token")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request.basic_auth("<username>", "<password>")
request["Content-Type"] = 'application/x-www-form-urlencoded'

response = http.request(request)
puts response.read_body
```

```java Generate Access Token - Staging
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.megaport.com/oauth2/token")
  .basicAuth("<username>", "<password>")
  .header("Content-Type", "application/x-www-form-urlencoded")
  .asString();
```

```php Generate Access Token - Staging
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.megaport.com/oauth2/token', [
  'form_params' => null,
  'headers' => [
    'Content-Type' => 'application/x-www-form-urlencoded',
  ],
    'auth' => ['<username>', '<password>'],
]);

echo $response->getBody();
```

```csharp Generate Access Token - Staging
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://api.megaport.com/oauth2/token");
client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
```

```swift Generate Access Token - Staging
import Foundation

let credentials = Data("<username>:<password>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/x-www-form-urlencoded"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://api.megaport.com/oauth2/token")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```