CTRLK

Authentication types and examples

|

View as Markdown

All API requests need to be authenticated through the Authorization header. The Infobip API offers the following authentication methods:

  • HTTP Basic authentication
  • API keys
  • IBSSO tokens
  • OAuth 2.0

Select your preferred method to suit your current tech stack and security requirement level. Many of these methods are vulnerable to man-in-the-middle attacks, so it is recommended to combine them with other security mechanisms such as an encrypted connection or SSL.

Refer to the Errors section to troubleshoot potential issues, or alternatively reach out to the Infobip Support team for help.

API key authentication

An API key is an access token that a client provides when making API calls. It is a simple way to secure access and thus the most popular authentication method used with REST APIs. The key can be sent in the query string or as a request header. You are automatically assigned an API Key once you create an account. Generate more keys and manage the existing ones through the Infobip API key management page.

Here are some key facts about this method:

  • API keys can be generated by calling the dedicated API method
  • Keys can be revoked at any time which is useful when separating the API access rights across multiple applications or use cases
  • Infobip API keys have a predefined expiry date to eventually become invalid

Example API Key Header - HTTP client

The examples below show how to specify the API Key authentication when using client libraries.

bash
1curl -L -g -X GET 'https://{baseUrl}/sms/3/reports' \
2 -H 'Authorization: App 003026abc133714df1834b8638bb496e-8f4b3d9a-e931-478d-a994-28a725159ab9'
java
1Request request = new Request.Builder()
2 .url("BASE_URL" + "sms/3/reports")
3 .addHeader("Authorization", "App " + apiKey)
4 .addHeader("Content-Type", "application/json")
5 .addHeader("Accept", "application/json")
6 .post(requestBody)
7 .build();
csharp
1HttpClient client = new HttpClient();
2client.BaseAddress = new Uri("BASE_URL");
3 
4client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("App", "API_KEY");
5client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Example API Key Header - API client library

The examples below show how to prepare an HTTP request using API Key authentication. Note this request is much simpler than using a basic authentication request.

java
1ApiClient apiClient = ApiClient.forApiKey(ApiKey.from(API_KEY))
2 .withBaseUrl(BaseUrl.from(BASE_URL))
3 .build();
csharp
1var configuration = new Configuration()
2{
3 BasePath = "BASE_URL",
4 ApiKeyPrefix = "App",
5 ApiKey = "API_KEY"
6};

API scopes on API keys

Each API key need to have scopes defined. You do it through your Infobip account. For more details on API scopes, see the dedicated API scopes section.

OAuth 2.0

This type of authentication is the most secure option and is almost industry standard. Similar to using IBSSO tokens, you will use an access token you get from separate endpoint.

Here are some key facts about this method:

  • The access token returned in response will expire within the time limit provided in seconds in the same response.
  • Infobip acts as both a resource and an authorization server.
  • A new token has to be created once the token expires. There is no automatic token retrieval.

For more details, see the official OAuth 2.0 ↗ specification.

How to use OAuth 2.0

  1. Make a call to get the access token and the expiration time from a separate endpoint.
  2. Include Bearer and the token in the Authorization header for all subsequent calls until the token expires. Authorization: Bearer {access_token}

HTTP requests to use with OAuth authentication

  • Create OAuth2 token

Obtain OAuth token

Similarly to IBSSO tokens, you have to first obtain a token before making any API calls.

Example OAuth Authentication - HTTP client

The examples below show how to prepare an HTTP client request with a header.

java
1Request request = new Request.Builder()
2 .url("BASE_URL" + "/sms/2/text/advanced")
3 .addHeader("Authorization", "Bearer " + accessToken)
4 .addHeader("Content-Type", "application/json")
5 .addHeader("Accept", "application/json")
6 .post(body)
7 .build();
csharp
1HttpClient client = new HttpClient();
2client.BaseAddress = new Uri("BASE_URL");
3 
4client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "ACCESS_TOKEN");
5client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Example OAuth Authentication - API library

The examples below show how to prepare an HTTP request with headers.

csharp
1var configuration = new Configuration()
2{
3 BasePath = "BASE_URL",
4 ApiKeyPrefix = "Bearer",
5 ApiKey = "ACCESS_TOKEN"
6};

IBSSO token authentication

IBSSO tokens are session-based meaning tokens are valid for a short amount of time. That ultimately makes this method more secure, but also requires more maintenance to keep authentication valid.

Typically, this kind of authentication is used in single sign-on scenarios where multiple sign-ins which to be avoided across the system. It may be also useful in scenarios when sensitive data needs to be handled centrally without the need to distribute it across various enterprise systems.

Here are some key facts about this method:

  • All API requests are authenticated with a session token
  • By default, IBSSO tokens will expire after 60 minutes after which a new token must be created
  • If you want to create a new token but the previous one has not expired yet, you will first need to destroy the session
  • You can shorten the session's length with a dedicated API call

How to use IBSSO tokens

  1. Make a call to create a session endpoint and take the token from the response.
  2. Include IBSSO and the token in the Authorization header for all subsequent calls: Authorization: IBSSO 2f9b4d31-2d0d-49a8-85f0-9b862bdca394
  3. Optionally, destroy the session to adjust the session's length to your needs. By default, the session will expire after 60 minutes.

HTTP requests to use with IBSSO token authentication

  • Create session
  • Destroy session

Obtain IBSSO token

Create a session by calling the Create session endpoint. The response will contain the token which can then be used in the HTTP header of the requests to other API endpoints such as Send SMS.

java
1private static class IbssoResponse {
2 public IbssoResponse() {
3 super();
4 }
5 
6 @JsonProperty("token")
7 public String token;
8 
9 @JsonGetter("token")
10 public String getToken() {
11 return token;
12 }
13 
14 @JsonSetter("token")
15 public void setToken(String token) {
16 this.token = token;
17 }
18}
19 
20String jsonBody = String.format("{\"username\":\"%s\",\"password\":\"%s\"}", "USERNAME", "PASSWORD");
21 
22RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);
23 
24Request request = new Request.Builder()
25 .url("BASE_URL" + "/auth/1/session")
26 .addHeader("Content-Type", "application/json")
27 .addHeader("Accept", "application/json")
28 .post(requestBody)
29 .build();
30 
31OkHttpClient httpClient = new OkHttpClient().newBuilder().build();
32Response response = httpClient.newCall(request).execute();
33String responseBody = response.body().string();
34System.out.println(responseBody);
35 
36IbssoResponse ibssoResponse = new ObjectMapper().readValue(responseBody, IbssoResponse.class);
37 
38return ibssoResponse.token;
csharp
1public class IbssoResponse
2{
3 [System.Text.Json.Serialization.JsonPropertyName("token")]
4 public string Token { get; set; }
5}
6 
7string username = "USERNAME";
8string password = "PASSWORD";
9 
10HttpClient client = new HttpClient();
11client.BaseAddress = new Uri("BASE_URL");
12client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
13 
14string body = $@"
15{{
16 ""username"": ""{username}"",
17 ""password"": ""{password}""
18}}";
19 
20HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, "/auth/1/session");
21httpRequest.Content = new StringContent(body, System.Text.Encoding.UTF8, "application/json");
22 
23var response = client.SendAsync(httpRequest).GetAwaiter().GetResult();
24var responseContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
25 
26var responseObject = JsonSerializer.Deserialize(responseContent);
27 
28return responseObject.Token;

Example IBSSO Token Authentication - HTTP client

The examples below show how to prepare the HTTP request. Note that this is almost identical to API Key authentication, but instead of App, you will use IBSSO in the header.

csharp
1HttpClient client = new HttpClient();
2client.BaseAddress = new Uri("BASE_URL");
3 
4client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("IBSSO", "TOKEN");
5client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Basic authentication

Basic authentication works by sending a username and password in every API request. Typically, this method is used in situations when the API key is not available. For example, API methods generating API keys could be authenticated with Basic.

Basic Auth is the least recommended method as it is still simple to decode encrypted credentials back to their original values. Refer to the HTTP Authentication resource ↗ to see how to restrict access to your server with Basic authentication.

IMPORTANT: Basic Auth credentials are Base64-encoded, which is easily reversible. Do not use it for production integrations. Use API key or OAuth 2.0 instead.

Here are some key facts about this method:

  • Built into HTTP protocol itself
  • Credentials should be encoded in a Base64 format (for example, with the RFC2045-MIME ↗ variant) and separated by a colon (:)
  • Encoded credentials are added to the header after Basic

Example Basic Auth Header - HTTP client

When using any of the Infobip API client libraries you don't have to manually encode the credentials. You only need to specify the username and password when creating an instance of a client object.

bash
1curl -X GET 'https://{baseUrl}/sms/1/reports' \
2 -H 'Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='

Example Basic Auth Header - API client library

When using any of the Infobip API client libraries you do not have to manually encode the credentials data like mentioned above. You only need to specify the username and password when creating an instance of a client object as shown in the example below.

csharp
1var configuration = new Configuration()
2{
3 BasePath = "BASE_URL",
4 Username = "USERNAME",
5 Password = "PASSWORD"
6};

API scopes on Basic Auth

For information on API scopes associated with Basic Auth, refer to the dedicated User roles and API scopes section.

Authentication errors

Commonly you will get the 401 Unauthorised HTTP status code in response when there is a missing or invalid username or password.

json
1{
2 "errorCode": "E401",
3 "description": "The request lacks valid authentication credentials for the requested resource.",
4 "action": "Check the resources and adjust authentication credentials.",
5 "violations": [],
6 "resources": [
7 {
8 "name": "API Authentication",
9 "url": "https://{baseUrl}/docs/api/essentials/api-authentication"
10 },
11 {
12 "name": "API endpoint documentation",
13 "url": "https://{baseUrl}/docs/api/get-outbound-sms-message-logs-v3"
14 }
15 ]
16}

Some older endpoint may still return an older version of the error.

json
1{
2 "requestError": {
3 "serviceException": {
4 "messageId": "UNAUTHORIZED",
5 "text": "Invalid login details"
6 }
7 }
8}

Library exceptions

When using one of the libraries, make sure to handle API exceptions.

java
1try {
2 SmsResponse smsResponse = sendSmsApi.sendSmsMessage(smsMessageRequest);
3} catch (ApiException apiException) {
4 apiException.getCode();
5 apiException.getResponseHeaders();
6 apiException.getResponseBody();
7}
csharp
1try
2{
3 var result = api.SendSmsMessage(smsRequest);
4}
5catch(ApiException apiException)
6{
7 var errorCode = apiException.ErrorCode;
8 var errorContent = apiException.ErrorContent;
9}

Next steps

Authorization and scope
Understand API scopes, how to assign them to keys, and how user roles map to scopes.

API security best practices
Recommendations for securing API keys, rotating credentials, and protecting your integration.

Error codes
Full reference of Infobip error codes and recommended actions.