This guide provides a comprehensive overview of authentication in the SMSGate API. JWT authentication is the primary mechanism for securing API access, providing a robust and scalable way to authenticate requests.
Authentication Overview 🔑
The SMSGate supports multiple authentication methods to accommodate different use cases:
Basic Authentication: Legacy username/password for backward compatibility
JWT Bearer Tokens: Primary authentication mechanism with configurable TTL
JWT Authentication Availability
JWT authentication is only available in Public Cloud Server mode. In Local Server mode, only Basic Authentication is supported.
JWT authentication is recommended for all new integrations as it provides better security, scalability, and fine-grained access control through scopes.
JWT Authentication 🔐
JWT authentication uses bearer tokens to authenticate API requests. These tokens contain encoded information about the user, their permissions (scopes), and token metadata.
Token Generation 🚀
To generate a JWT token, make a POST request to the token endpoint using Basic Authentication.
Endpoint
POST /3rdparty/v1/auth/token
Local Server Mode
This endpoint returns HTTP 501 Not Implemented in local server mode. Use Basic Authentication instead.
# JWT authentication example# First, get a tokentoken_response=requests.post("https://api.sms-gate.app/3rdparty/v1/auth/token",auth=("username","password"),json={"ttl":3600,"scopes":["messages:send"]})iftoken_response.status_code==201:token_data=token_response.json()access_token=token_data["access_token"]# Then use the tokenresponse=requests.post("https://api.sms-gate.app/3rdparty/v1/messages",headers={"Authorization":f"Bearer {access_token}","Content-Type":"application/json"},json={"phoneNumbers":["+1234567890"],"textMessage":{"text":"Hello world!"}})
Error Handling ⚠️
Error Handling Best Practices
Check Token Expiration: Implement token refresh before expiration
Handle 401 Errors: Re-authenticate and get a new token
Handle 403 Errors: Verify your token has the required scopes
Log Errors: Record authentication errors for debugging
Error Handling Example (Python)
importrequestsimporttimefromdatetimeimportdatetime,timedeltaclassSMSGatewayClient:def__init__(self,gateway_url,username,password):self.gateway_url=gateway_urlself.username=usernameself.password=passwordself.access_token=Noneself.token_expires_at=Nonedefget_token(self,scopes,ttl=3600):"""Get a new JWT token"""response=requests.post(f"{self.gateway_url}/3rdparty/v1/auth/token",auth=(self.username,self.password),headers={"Content-Type":"application/json"},json={"ttl":ttl,"scopes":scopes})ifresponse.status_code==201:token_data=response.json()self.access_token=token_data["access_token"]# Parse expiration timeself.token_expires_at=datetime.fromisoformat(token_data["expires_at"].replace("Z","+00:00"))returnself.access_tokenelse:raiseException(f"Failed to get token: {response.status_code} - {response.text}")defensure_valid_token(self,scopes):"""Ensure we have a valid token, refresh if needed"""if(self.access_tokenisNoneorself.token_expires_atisNoneordatetime.now()+timedelta(minutes=5)>=self.token_expires_at):self.get_token(scopes)returnself.access_tokendefsend_message(self,recipient,message):"""Send a message with automatic token handling"""try:token=self.ensure_valid_token(["messages:send"])response=requests.post(f"{self.gateway_url}/3rdparty/v1/messages",headers={"Authorization":f"Bearer {token}","Content-Type":"application/json"},json={"recipient":recipient,"textMessage":{"text":message}})ifresponse.status_code==401:# Token might be expired or invalid, try once moretoken=self.get_token(["messages:send"])response=requests.post(f"{self.gateway_url}/3rdparty/v1/messages",headers={"Authorization":f"Bearer {token}","Content-Type":"application/json"},json={"recipient":recipient,"textMessage":{"text":message}})ifresponse.status_code==202:returnresponse.json()else:raiseException(f"Failed to send message: {response.status_code} - {response.text}")exceptExceptionase:print(f"Error sending message: {str(e)}")raise# Usage exampleclient=SMSGatewayClient("https://api.sms-gate.app","username","password")result=client.send_message("+1234567890","Hello from JWT!")print("Message sent:",result)
Security Considerations 🔒
Token Security
Keep Tokens Secret: Treat JWT tokens like passwords
Use HTTPS: Always transmit tokens over encrypted connections
Short Expiration: Use the shortest practical TTL for your use case
Scope Limitation: Request only the scopes you need
Secure Storage: Store tokens securely on the server side, not in client-side code
Revocation: Implement token revocation for compromised tokens
Client Security
Validate Tokens: Always validate server responses
Error Handling: Implement proper error handling for authentication failures