🎯 Passo 4: Usando o Token nas Requisições
Agora que você obteve suas credenciais e sabe gerar tokens, o próximo passo é usá-los corretamente nas chamadas às APIs da Credsystem.
As URLs nos exemplos abaixo são ilustrativas. Substitua pelas URLs reais que você recebeu no SharePoint (ambiente, realm, endpoints, etc.).
📖 Como Funciona o Fluxo
- Gerar Token → Autenticar com suas credenciais
- Armazenar Token → Manter em cache enquanto válido
- Usar Token → Incluir no header
Authorization: Bearer {token} - Renovar Token → Quando expirar ou receber erro 401
- Chamar API → Fazer requisições com token válido
Este documento mostra exemplos completos de classes de autenticação que gerenciam todo esse fluxo automaticamente.
🎭 Cenários de Uso
Servidor Backend (Recomendado)
Frontend → Backend → [Auth + Token] → API Credsystem
✅ Seguro - Credenciais no backend
✅ Performático - Cache de token compartilhado
✅ Controlado - Você gerencia toda autenticação
Servidor-a-Servidor
Seu Servidor → [Auth + Token] → API Credsystem
✅ Ideal para integrações automatizadas
✅ Sem interação de usuário
✅ Client Credentials Grant
❌ Frontend Direto (NÃO FAZER)
Browser Frontend → [Auth + Token] → API Credsystem
❌ Inseguro - Expõe credenciais no navegador
❌ CORS - Pode ter problemas
❌ Não recomendado pela Credsystem
💡 Conceitos Importantes
✅ O que fazer:
- Reutilizar token enquanto válido (implementar cache)
- Renovar automaticamente antes de expirar
- Tratar erro 401 (token expirado) e tentar novamente
- Armazenar token APENAS no backend (nunca frontend)
❌ O que NÃO fazer:
- Gerar novo token a cada requisição (desperdiça recursos)
- Armazenar token no localStorage/sessionStorage do navegador
- Ignorar erros 401 sem renovar token
🔧 Classe de Autenticação Completa
Estas classes gerenciam automaticamente:
- ✅ Cache de token válido (reutilização)
- ✅ Renovação automática quando expira
- ✅ Retry automático em caso de erro 401
- ✅ Margem de segurança de 30s antes da expiração
- ✅ Tratamento de erros robusto
Escolha a linguagem e copie a classe completa para seu projeto:
- JavaScript
- Python
- Java
- C#
- PHP
- Go
// Classe completa para gerenciar autenticação
class CredsystemAuth {
constructor(clientId, clientSecret) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.token = null;
this.tokenExpiry = null;
}
// Gerar ou reutilizar token
async getToken() {
// Reutilizar token se ainda válido
if (this.token && this.tokenExpiry > Date.now()) {
console.log('✅ Reutilizando token válido');
return this.token;
}
console.log('🔄 Gerando novo token...');
const response = await fetch(
'https://ssoprd.credsystem.com.br/auth/realms/credsystem/protocol/openid-connect/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,
}),
}
);
if (!response.ok) {
throw new Error(`Erro ao gerar token: ${response.status}`);
}
const data = await response.json();
this.token = data.access_token;
// Definir expiração 30s antes (margem de segurança)
this.tokenExpiry = Date.now() + (data.expires_in - 30) * 1000;
console.log('✅ Token gerado com sucesso!');
return this.token;
}
// Fazer requisição à API com token
async callAPI(endpoint, method = 'GET', body = null) {
const token = await this.getToken();
const options = {
method,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
};
if (body) {
options.body = JSON.stringify(body);
}
const response = await fetch(endpoint, options);
// Tratar token expirado - renovar e tentar novamente
if (response.status === 401) {
console.log('⚠️ Token expirado, gerando novo...');
this.token = null; // Forçar novo token
return this.callAPI(endpoint, method, body); // Retry
}
return response;
}
}
// ========================================
// EXEMPLO DE USO
// ========================================
const auth = new CredsystemAuth(
process.env.CREDSYSTEM_CLIENT_ID,
process.env.CREDSYSTEM_CLIENT_SECRET
);
// Fazer chamada à API
const response = await auth.callAPI('https://api.credsystem.com.br/v1/exemplo');
const data = await response.json();
console.log(data);
// O token será reutilizado em chamadas subsequentes
const response2 = await auth.callAPI('https://api.credsystem.com.br/v1/outro-endpoint');
import requests
from datetime import datetime, timedelta
class CredsystemAuth:
def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret
self.token = None
self.token_expiry = None
# Gerar ou reutilizar token
def get_token(self):
# Reutilizar token se ainda válido
if self.token and self.token_expiry > datetime.now():
print('✅ Reutilizando token válido')
return self.token
print('🔄 Gerando novo token...')
url = "https://ssoprd.credsystem.com.br/auth/realms/credsystem/protocol/openid-connect/token"
payload = {
'grant_type': 'client_credentials',
'client_id': self.client_id,
'client_secret': self.client_secret
}
response = requests.post(url, data=payload)
if response.status_code != 200:
raise Exception(f'Erro ao gerar token: {response.status_code}')
data = response.json()
self.token = data['access_token']
# Definir expiração 30s antes (margem de segurança)
self.token_expiry = datetime.now() + timedelta(seconds=data['expires_in'] - 30)
print('✅ Token gerado com sucesso!')
return self.token
# Fazer requisição à API com token
def call_api(self, endpoint, method='GET', json_data=None):
token = self.get_token()
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
response = requests.request(method, endpoint, headers=headers, json=json_data)
# Tratar token expirado - renovar e tentar novamente
if response.status_code == 401:
print('⚠️ Token expirado, gerando novo...')
self.token = None # Forçar novo token
return self.call_api(endpoint, method, json_data) # Retry
return response
# ========================================
# EXEMPLO DE USO
# ========================================
import os
auth = CredsystemAuth(
os.getenv('CREDSYSTEM_CLIENT_ID'),
os.getenv('CREDSYSTEM_CLIENT_SECRET')
)
# Fazer chamada à API
response = auth.call_api('https://api.credsystem.com.br/v1/exemplo')
data = response.json()
print(data)
# O token será reutilizado em chamadas subsequentes
response2 = auth.call_api('https://api.credsystem.com.br/v1/outro-endpoint')
import java.net.http.*;
import java.net.URI;
import java.time.Instant;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
// Classe completa para gerenciar autenticação
public class CredsystemAuth {
private String clientId;
private String clientSecret;
private String token;
private Instant tokenExpiry;
private static final HttpClient client = HttpClient.newHttpClient();
public CredsystemAuth(String clientId, String clientSecret) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.token = null;
this.tokenExpiry = null;
}
// Gerar ou reutilizar token
public String getToken() throws Exception {
// Reutilizar token se ainda válido
if (token != null && tokenExpiry != null && Instant.now().isBefore(tokenExpiry)) {
System.out.println("✅ Reutilizando token válido");
return token;
}
System.out.println("🔄 Gerando novo token...");
String body = "grant_type=client_credentials" +
"&client_id=" + clientId +
"&client_secret=" + clientSecret;
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://ssoprd.credsystem.com.br/auth/realms/credsystem/protocol/openid-connect/token"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new Exception("Erro ao gerar token: " + response.statusCode());
}
JsonObject jsonObject = JsonParser.parseString(response.body()).getAsJsonObject();
this.token = jsonObject.get("access_token").getAsString();
// Definir expiração 30s antes (margem de segurança)
int expiresIn = jsonObject.get("expires_in").getAsInt();
this.tokenExpiry = Instant.now().plusSeconds(expiresIn - 30);
System.out.println("✅ Token gerado com sucesso!");
return this.token;
}
// Fazer requisição à API com token
public HttpResponse<String> callAPI(String endpoint, String method, String jsonBody) throws Exception {
String authToken = getToken();
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
.uri(URI.create(endpoint))
.header("Authorization", "Bearer " + authToken)
.header("Content-Type", "application/json");
if ("POST".equals(method) && jsonBody != null) {
requestBuilder.POST(HttpRequest.BodyPublishers.ofString(jsonBody));
} else if ("PUT".equals(method) && jsonBody != null) {
requestBuilder.PUT(HttpRequest.BodyPublishers.ofString(jsonBody));
} else {
requestBuilder.GET();
}
HttpResponse<String> response = client.send(requestBuilder.build(),
HttpResponse.BodyHandlers.ofString());
// Tratar token expirado - renovar e tentar novamente
if (response.statusCode() == 401) {
System.out.println("⚠️ Token expirado, gerando novo...");
this.token = null; // Forçar novo token
return callAPI(endpoint, method, jsonBody); // Retry
}
return response;
}
// ========================================
// EXEMPLO DE USO
// ========================================
public static void main(String[] args) {
try {
CredsystemAuth auth = new CredsystemAuth(
System.getenv("CREDSYSTEM_CLIENT_ID"),
System.getenv("CREDSYSTEM_CLIENT_SECRET")
);
// Fazer chamada à API
HttpResponse<String> response = auth.callAPI(
"https://api.credsystem.com.br/v1/exemplo",
"GET",
null
);
System.out.println("Resposta: " + response.body());
// O token será reutilizado em chamadas subsequentes
HttpResponse<String> response2 = auth.callAPI(
"https://api.credsystem.com.br/v1/outro-endpoint",
"GET",
null
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
// Classe completa para gerenciar autenticação
public class CredsystemAuth
{
private readonly string clientId;
private readonly string clientSecret;
private string token;
private DateTime tokenExpiry;
private static readonly HttpClient httpClient = new HttpClient();
public CredsystemAuth(string clientId, string clientSecret)
{
this.clientId = clientId;
this.clientSecret = clientSecret;
this.token = null;
this.tokenExpiry = DateTime.MinValue;
}
// Gerar ou reutilizar token
public async Task<string> GetToken()
{
// Reutilizar token se ainda válido
if (token != null && DateTime.Now < tokenExpiry)
{
Console.WriteLine("✅ Reutilizando token válido");
return token;
}
Console.WriteLine("🔄 Gerando novo token...");
var values = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", clientId },
{ "client_secret", clientSecret }
};
var content = new FormUrlEncodedContent(values);
var response = await httpClient.PostAsync(
"https://ssoprd.credsystem.com.br/auth/realms/credsystem/protocol/openid-connect/token",
content
);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Erro ao gerar token: {response.StatusCode}");
}
var responseString = await response.Content.ReadAsStringAsync();
var jsonDoc = JsonDocument.Parse(responseString);
token = jsonDoc.RootElement.GetProperty("access_token").GetString();
int expiresIn = jsonDoc.RootElement.GetProperty("expires_in").GetInt32();
// Definir expiração 30s antes (margem de segurança)
tokenExpiry = DateTime.Now.AddSeconds(expiresIn - 30);
Console.WriteLine("✅ Token gerado com sucesso!");
return token;
}
// Fazer requisição à API com token
public async Task<HttpResponseMessage> CallAPI(string endpoint, HttpMethod method, object bodyData = null)
{
string authToken = await GetToken();
var request = new HttpRequestMessage(method, endpoint);
request.Headers.Add("Authorization", $"Bearer {authToken}");
if (bodyData != null)
{
var jsonContent = JsonSerializer.Serialize(bodyData);
request.Content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
}
var response = await httpClient.SendAsync(request);
// Tratar token expirado - renovar e tentar novamente
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
Console.WriteLine("⚠️ Token expirado, gerando novo...");
token = null; // Forçar novo token
return await CallAPI(endpoint, method, bodyData); // Retry
}
return response;
}
// ========================================
// EXEMPLO DE USO
// ========================================
public static async Task Main()
{
var auth = new CredsystemAuth(
Environment.GetEnvironmentVariable("CREDSYSTEM_CLIENT_ID"),
Environment.GetEnvironmentVariable("CREDSYSTEM_CLIENT_SECRET")
);
// Fazer chamada à API
var response = await auth.CallAPI(
"https://api.credsystem.com.br/v1/exemplo",
HttpMethod.Get
);
var data = await response.Content.ReadAsStringAsync();
Console.WriteLine(data);
// O token será reutilizado em chamadas subsequentes
var response2 = await auth.CallAPI(
"https://api.credsystem.com.br/v1/outro-endpoint",
HttpMethod.Get
);
}
}
<?php
// Classe completa para gerenciar autenticação
class CredsystemAuth {
private $clientId;
private $clientSecret;
private $token = null;
private $tokenExpiry = null;
public function __construct($clientId, $clientSecret) {
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
}
// Gerar ou reutilizar token
public function getToken() {
// Reutilizar token se ainda válido
if ($this->token && $this->tokenExpiry > time()) {
echo "✅ Reutilizando token válido\n";
return $this->token;
}
echo "🔄 Gerando novo token...\n";
$url = "https://ssoprd.credsystem.com.br/auth/realms/credsystem/protocol/openid-connect/token";
$data = array(
'grant_type' => 'client_credentials',
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = @file_get_contents($url, false, $context);
if ($result === FALSE) {
throw new Exception('Erro ao gerar token');
}
$response = json_decode($result, true);
$this->token = $response['access_token'];
// Definir expiração 30s antes (margem de segurança)
$this->tokenExpiry = time() + $response['expires_in'] - 30;
echo "✅ Token gerado com sucesso!\n";
return $this->token;
}
// Fazer requisição à API com token
public function callAPI($endpoint, $method = 'GET', $bodyData = null) {
$token = $this->getToken();
$headers = array(
"Authorization: Bearer " . $token,
"Content-Type: application/json"
);
$options = array(
'http' => array(
'header' => implode("\r\n", $headers),
'method' => $method,
'ignore_errors' => true
)
);
if ($bodyData !== null) {
$options['http']['content'] = json_encode($bodyData);
}
$context = stream_context_create($options);
$result = @file_get_contents($endpoint, false, $context);
// Verificar se houve erro 401
if (isset($http_response_header)) {
foreach($http_response_header as $header) {
if (strpos($header, '401') !== false) {
echo "⚠️ Token expirado, gerando novo...\n";
$this->token = null; // Forçar novo token
return $this->callAPI($endpoint, $method, $bodyData); // Retry
}
}
}
return json_decode($result, true);
}
}
// ========================================
// EXEMPLO DE USO
// ========================================
$auth = new CredsystemAuth(
getenv('CREDSYSTEM_CLIENT_ID'),
getenv('CREDSYSTEM_CLIENT_SECRET')
);
// Fazer chamada à API
$response = $auth->callAPI('https://api.credsystem.com.br/v1/exemplo');
print_r($response);
// O token será reutilizado em chamadas subsequentes
$response2 = $auth->callAPI('https://api.credsystem.com.br/v1/outro-endpoint');
?>
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"time"
)
// Estrutura de resposta do token
type TokenResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
// Classe completa para gerenciar autenticação
type CredsystemAuth struct {
ClientID string
ClientSecret string
Token string
TokenExpiry time.Time
HTTPClient *http.Client
}
// Construtor
func NewCredsystemAuth(clientID, clientSecret string) *CredsystemAuth {
return &CredsystemAuth{
ClientID: clientID,
ClientSecret: clientSecret,
HTTPClient: &http.Client{},
}
}
// Gerar ou reutilizar token
func (auth *CredsystemAuth) GetToken() (string, error) {
// Reutilizar token se ainda válido
if auth.Token != "" && time.Now().Before(auth.TokenExpiry) {
fmt.Println("✅ Reutilizando token válido")
return auth.Token, nil
}
fmt.Println("🔄 Gerando novo token...")
authURL := "https://ssoprd.credsystem.com.br/auth/realms/credsystem/protocol/openid-connect/token"
data := url.Values{}
data.Set("grant_type", "client_credentials")
data.Set("client_id", auth.ClientID)
data.Set("client_secret", auth.ClientSecret)
req, err := http.NewRequest("POST", authURL, bytes.NewBufferString(data.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := auth.HTTPClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return "", fmt.Errorf("erro ao gerar token: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var tokenResp TokenResponse
if err := json.Unmarshal(body, &tokenResp); err != nil {
return "", err
}
auth.Token = tokenResp.AccessToken
// Definir expiração 30s antes (margem de segurança)
auth.TokenExpiry = time.Now().Add(time.Duration(tokenResp.ExpiresIn-30) * time.Second)
fmt.Println("✅ Token gerado com sucesso!")
return auth.Token, nil
}
// Fazer requisição à API com token
func (auth *CredsystemAuth) CallAPI(endpoint, method string, bodyData interface{}) ([]byte, error) {
token, err := auth.GetToken()
if err != nil {
return nil, err
}
var reqBody []byte
if bodyData != nil {
reqBody, err = json.Marshal(bodyData)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, endpoint, bytes.NewBuffer(reqBody))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := auth.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Tratar token expirado - renovar e tentar novamente
if resp.StatusCode == 401 {
fmt.Println("⚠️ Token expirado, gerando novo...")
auth.Token = "" // Forçar novo token
return auth.CallAPI(endpoint, method, bodyData) // Retry
}
return ioutil.ReadAll(resp.Body)
}
// ========================================
// EXEMPLO DE USO
// ========================================
func main() {
auth := NewCredsystemAuth(
os.Getenv("CREDSYSTEM_CLIENT_ID"),
os.Getenv("CREDSYSTEM_CLIENT_SECRET"),
)
// Fazer chamada à API
response, err := auth.CallAPI(
"https://api.credsystem.com.br/v1/exemplo",
"GET",
nil,
)
if err != nil {
fmt.Printf("Erro: %v\n", err)
return
}
fmt.Printf("Resposta: %s\n", response)
// O token será reutilizado em chamadas subsequentes
response2, _ := auth.CallAPI(
"https://api.credsystem.com.br/v1/outro-endpoint",
"GET",
nil,
)
fmt.Printf("Resposta 2: %s\n", response2)
}
🎯 Próximos Passos
Agora que você domina o uso de tokens:
👉 Segurança e Boas Práticas - Aprofunde em proteção de credenciais
👉 Troubleshooting - Solucione problemas comuns
Ou volte para o Índice de Autenticação