# Autenticazione
## Recuperare il token
Per recuperare il token fare una richiesta all'endpoint passando il client_id come nome utente e il client_secret come password in Http Basic Authentication

:::info
Il server OAuth2 cambia in base all'ambiente: `https://authnew.jatapay.it` in produzione e `https://authdpop.jatapay.it` in test.
:::

## Richiesta Http
## Richiesta Http
```bash
POST https://authnew.jatapay.it/token
```
:::warning
 La richiesta deve avere l'header Content-Type: application/json e includere il parametro nel corpo del JSON
:::

## Parametri
| Parametro | Richiesto | Descrizione |
| -------------- | -------------- | -------------- |
| grant_type   | Sì   | Settare a 'client_credentials' per ottenere il token con le credenziali   |

**Shell**

  ```bash
  # Passare il client id e il client secret come username e password in http Basic Authentication
  curl "https://authnew.jatapay.it/token" \
  -H "Content-Type: application/json" \
  -H "Authorization: Basic client_id:client_secret" #client_id:client_secret codificato in base64 \
  -d '{"grant_type": "client_credentials"}'
  ```

**PHP**

    ```php
$client_id = 'IL MIO CLIENT ID';
$client_secret = 'IL MIO CLIENT_SECRET';
$data = json_encode(array(
            'grant_type' => 'client_credentials'
          ));

$url = curl_init("https://authnew.jatapay.it/token");

curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_POSTFIELDS, $data);
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json',
      'Content-Length: ' . strlen($data),
      'Authorization: Basic '. base64_encode($client_id. ":" . $client_secret))
  ));

$result = curl_exec($url);

curl_close($url);

$api_response = json_decode($result);

$token = $api_response->token;
```

**Python**

```python
import requests
import json
import base64
url = "https://authnew.jatapay.it/token"
client_id = 'IL MIO CLIENT_ID'
client_secret = 'IL MIO CLIENT_SECRET'
encoded = client_id + ':' + client_secret
encoded = encoded.encode()
encoded = base64.b64encode(encoded).decode()
data = json.dumps({
  "grant_type": "client_credentials"
})
headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Basic ' + encoded
}

response = requests.request("POST", url, headers=headers, data=data).json()

print(response)

```
**Node.js**

```javascript
const clientId = 'IL_MIO_CLIENT_ID';
const clientSecret = 'IL_MIO_CLIENT_SECRET';

const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');

const response = await fetch('https://authnew.jatapay.it/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Basic ${credentials}`
  },
  body: JSON.stringify({ grant_type: 'client_credentials' })
});

const data = await response.json();
console.log(data.token);
```

**Go**

```go
package main

import (
	"encoding/base64"
	"fmt"
	"io"
	"net/http"
	"strings"
)

func main() {
	clientId := "IL_MIO_CLIENT_ID"
	clientSecret := "IL_MIO_CLIENT_SECRET"
	credentials := base64.StdEncoding.EncodeToString([]byte(clientId + ":" + clientSecret))

	body := `{"grant_type": "client_credentials"}`

	req, err := http.NewRequest("POST", "https://authnew.jatapay.it/token", strings.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Basic "+credentials)

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(data))
}
```

**.NET**

```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        const string clientId = "IL_MIO_CLIENT_ID";
        const string clientSecret = "IL_MIO_CLIENT_SECRET";

        var basic = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basic);

        var content = new StringContent("""{"grant_type": "client_credentials"}""", Encoding.UTF8, "application/json");
        var response = await client.PostAsync("https://authnew.jatapay.it/token", content);

        var json = await response.Content.ReadAsStringAsync();

        using var document = JsonDocument.Parse(json);
        Console.WriteLine(document.RootElement.GetProperty("token").GetString());
    }
}
```

**Java**

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Main {
    public static void main(String[] args) throws Exception {
        String clientId = "IL_MIO_CLIENT_ID";
        String clientSecret = "IL_MIO_CLIENT_SECRET";

        String basic = Base64.getEncoder()
                .encodeToString((clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://authnew.jatapay.it/token"))
                .header("Content-Type", "application/json")
                .header("Authorization", "Basic " + basic)
                .POST(HttpRequest.BodyPublishers.ofString("{\"grant_type\": \"client_credentials\"}"))
                .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
```

Il comando ritornerà un JSON con questa struttura:
```JSON

  {
    "refresh_token": "IL_REFRESH_TOKEN",
    "token": "IL_TOKEN_DI_ACCESSO"
  }

```

## Usare il token

Il valore di `token` va inviato nell'header `Authorization: Bearer IL_TOKEN_DI_ACCESSO` di ogni chiamata alle API.
Il `refresh_token` permette di ottenere un nuovo token di accesso senza ripetere l'autenticazione con le credenziali del client.

:::info
Le credenziali `client_id` e `client_secret` si possono leggere e rigenerare anche via Dashboard o via API
con gli endpoint `GET /api_credentials` e `POST /api_credentials`.
:::

## Autenticazione con client assertion

In alternativa al `client_secret` puoi autenticarti con una **client assertion**: un JWT firmato con la tua chiave
privata, che JataPay verifica usando la chiave pubblica pubblicata sul tuo `jwks_uri`.

### Configurazione

1. Abilita `enable_client_assertion` e imposta il `jwks_uri` nelle
   [Opzioni sviluppatore](/riferimento-api/opzioni-sviluppatore), dall'oggetto `authorization`: si possono aggiornare
   dalla Dashboard nella sezione **[Sviluppatori](https://dashboard.jatapay.it/sviluppatori)** oppure con
   `POST /esercente/developer_options`.
2. Pubblica il JWKS con la chiave pubblica all'URL indicato in `jwks_uri`.
3. Firma un JWT con la chiave privata e invialo come `client_assertion`.

Il `client_id` resta quello delle tue credenziali: cambia solo il modo in cui il client si autentica.

### Parametri della richiesta

| Parametro | Richiesto | Descrizione |
| -------------- | -------------- | -------------- |
| grant_type   | Sì   | Sempre `client_credentials`   |
| client_assertion_type   | Sì   | `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`   |
| client_assertion   | Sì   | Il JWT firmato con la chiave privata   |

Il corpo deve essere inviato come JSON (`Content-Type: application/json`), come per l'autenticazione con
`client_secret`.

### Claim del JWT

| Claim | Valore |
| -------------- | -------------- |
| iss   | Il `client_id`   |
| sub   | Il `client_id`   |
| client_id   | Il `client_id` (lo stesso valore di `iss` e `sub`)   |
| aud   | L'URL dell'endpoint del token (`https://authnew.jatapay.it/token`)   |
| iat   | Timestamp di emissione   |
| exp   | Timestamp di scadenza (al massimo 5 minuti dopo `iat`)   |
| jti   | Un identificativo univoco del JWT   |

L'header del JWT deve contenere `alg: RS256`, `typ: JWT` e il `kid` della chiave pubblicata nel JWKS.

**Shell**

```bash
# 1. Header e payload del JWT in base64url
header=$(printf '{"alg":"RS256","typ":"JWT","kid":"IL_MIO_KEY_ID"}' | openssl base64 -A | tr '+/' '-_' | tr -d '=')
now=$(date +%s)
payload=$(printf '{"iss":"IL_MIO_CLIENT_ID","sub":"IL_MIO_CLIENT_ID","client_id":"IL_MIO_CLIENT_ID","aud":"https://authnew.jatapay.it/token","iat":%s,"exp":%s,"jti":"%s"}' "$now" "$((now + 300))" "$(uuidgen)" | openssl base64 -A | tr '+/' '-_' | tr -d '=')

# 2. Firma RS256 con la chiave privata
signing_input="$header.$payload"
signature=$(printf '%s' "$signing_input" | openssl dgst -sha256 -sign chiave_privata.pem | openssl base64 -A | tr '+/' '-_' | tr -d '=')
jwt="$signing_input.$signature"

# 3. Richiesta del token
curl -X POST "https://authnew.jatapay.it/token" \
  -H "Content-Type: application/json" \
  -d "{\"grant_type\":\"client_credentials\",\"client_assertion_type\":\"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\"client_assertion\":\"$jwt\"}"
```

**PHP**

```php
$client_id = 'IL_MIO_CLIENT_ID';
$key_id = 'IL_MIO_KEY_ID';
$token_url = 'https://authnew.jatapay.it/token';

function base64url($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$private_key = openssl_pkey_get_private(file_get_contents('chiave_privata.pem'));
$now = time();

$header = base64url(json_encode(array(
    'alg' => 'RS256',
    'typ' => 'JWT',
    'kid' => $key_id
)));

$claims = base64url(json_encode(array(
    'iss' => $client_id,
    'sub' => $client_id,
    'client_id' => $client_id,
    'aud' => $token_url,
    'iat' => $now,
    'exp' => $now + 300,
    'jti' => bin2hex(random_bytes(16))
)));

openssl_sign($header . '.' . $claims, $firma, $private_key, OPENSSL_ALGO_SHA256);
$jwt = $header . '.' . $claims . '.' . base64url($firma);

$body = json_encode(array(
    'grant_type' => 'client_credentials',
    'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
    'client_assertion' => $jwt
));

$url = curl_init($token_url);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($url, CURLOPT_POSTFIELDS, $body);
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$result = curl_exec($url);
curl_close($url);
$api_response = json_decode($result);

$token = $api_response->token;
```

**Python**

```python
import time
import uuid

import jwt  # PyJWT
import requests

client_id = 'IL_MIO_CLIENT_ID'
key_id = 'IL_MIO_KEY_ID'
token_url = 'https://authnew.jatapay.it/token'

with open('chiave_privata.pem') as f:
    private_key = f.read()

now = int(time.time())

assertion = jwt.encode(
    {
        'iss': client_id,
        'sub': client_id,
        'client_id': client_id,
        'aud': token_url,
        'iat': now,
        'exp': now + 300,
        'jti': str(uuid.uuid4()),
    },
    private_key,
    algorithm='RS256',
    headers={'kid': key_id},
)

response = requests.post(token_url, json={
    'grant_type': 'client_credentials',
    'client_assertion_type': 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
    'client_assertion': assertion,
}).json()

print(response)
```

**Node.js**

```javascript
const fs = require('node:fs');
const crypto = require('node:crypto');
const jwt = require('jsonwebtoken');

const clientId = 'IL_MIO_CLIENT_ID';
const keyId = 'IL_MIO_KEY_ID';
const tokenUrl = 'https://authnew.jatapay.it/token';

const privateKey = fs.readFileSync('chiave_privata.pem');

const assertion = jwt.sign({client_id: clientId}, privateKey, {
  algorithm: 'RS256',
  keyid: keyId,
  issuer: clientId,
  subject: clientId,
  audience: tokenUrl,
  jwtid: crypto.randomUUID(),
  expiresIn: 300
});

const response = await fetch(tokenUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    grant_type: 'client_credentials',
    client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
    client_assertion: assertion
  })
});

console.log(await response.json());
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

func main() {
	clientId := "IL_MIO_CLIENT_ID"
	keyId := "IL_MIO_KEY_ID"
	tokenURL := "https://authnew.jatapay.it/token"

	keyData, err := os.ReadFile("chiave_privata.pem")
	if err != nil {
		panic(err)
	}
	privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(keyData)
	if err != nil {
		panic(err)
	}

	now := time.Now()
	claims := jwt.MapClaims{
		"iss": clientId,
		"sub": clientId,
		"client_id": clientId,
		"aud": tokenURL,
		"iat": now.Unix(),
		"exp": now.Add(5 * time.Minute).Unix(),
		"jti": fmt.Sprintf("%d", now.UnixNano()),
	}

	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
	token.Header["kid"] = keyId

	assertion, err := token.SignedString(privateKey)
	if err != nil {
		panic(err)
	}

	payload, err := json.Marshal(map[string]string{
		"grant_type":            "client_credentials",
		"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
		"client_assertion":      assertion,
	})
	if err != nil {
		panic(err)
	}

	res, err := http.Post(tokenURL, "application/json", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.StatusCode, string(data))
}
```

**.NET**

```csharp
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Tokens;

class Program
{
    static async Task Main()
    {
        const string clientId = "IL_MIO_CLIENT_ID";
        const string keyId = "IL_MIO_KEY_ID";
        const string tokenUrl = "https://authnew.jatapay.it/token";

        using var rsa = RSA.Create();
        rsa.ImportFromPem(File.ReadAllText("chiave_privata.pem"));

        var credentials = new SigningCredentials(
            new RsaSecurityKey(rsa) {KeyId = keyId},
            SecurityAlgorithms.RsaSha256);

        var now = DateTimeOffset.UtcNow;
        var descriptor = new SecurityTokenDescriptor
        {
            Issuer = clientId,
            Audience = tokenUrl,
            IssuedAt = now.UtcDateTime,
            Expires = now.AddMinutes(5).UtcDateTime,
            Subject = new ClaimsIdentity(new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, clientId),
                new Claim("client_id", clientId),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            }),
            SigningCredentials = credentials
        };

        var assertion = new JwtSecurityTokenHandler().CreateEncodedJwt(descriptor);

        var payload = JsonSerializer.Serialize(new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
            ["client_assertion"] = assertion
        });

        using var client = new HttpClient();
        var response = await client.PostAsync(tokenUrl, new StringContent(payload, Encoding.UTF8, "application/json"));

        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}
```

**Java**

```java
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Date;
import java.util.UUID;

public class Main {
    public static void main(String[] args) throws Exception {
        String clientId = "IL_MIO_CLIENT_ID";
        String keyId = "IL_MIO_KEY_ID";
        String tokenUrl = "https://authnew.jatapay.it/token";

        RSAKey rsaKey = RSAKey.parseFromPEMEncodedObjects(Files.readString(Path.of("chiave_privata.pem")));
        Instant now = Instant.now();

        JWTClaimsSet claims = new JWTClaimsSet.Builder()
                .issuer(clientId)
                .subject(clientId)
                .claim("client_id", clientId)
                .audience(tokenUrl)
                .issueTime(Date.from(now))
                .expirationTime(Date.from(now.plusSeconds(300)))
                .jwtID(UUID.randomUUID().toString())
                .build();

        SignedJWT assertion = new SignedJWT(
                new JWSHeader.Builder(JWSAlgorithm.RS256)
                        .keyID(keyId)
                        .type(JOSEObjectType.JWT)
                        .build(),
                claims);
        assertion.sign(new RSASSASigner(rsaKey));

        String body = String.format(
                "{\"grant_type\":\"client_credentials\","
                        + "\"client_assertion_type\":\"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\","
                        + "\"client_assertion\":\"%s\"}",
                assertion.serialize());

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(tokenUrl))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
```
