Machine-to-Machine (M2M) authentication

There are many scenarios where applications, such as CLIs, or Backend services, need to call other APIs and when these APIs requires an access token the application must be able to authenticate itself (if the call isn’t done on behalf of a user). The Client Credentials Flow (defined in OAuth 2.0) allows an application to exchange its credentials, commonly a Client ID and Client Secret for an access token.

Exchange Client Credentials for an Access Token

To exchange the client credentials for an access token the Token endpoint is used.

POST /connect/token HTTP/1.1
Host: YOURINSTANCE.irmciam.se
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
 &client_id=THE_CLIENT_ID
 &client_secret=THE_CLIENT_SECRET
 &scope=THE_SCOPES_REQUIRED_TO_CALL_THE_API

C# Example

In this example code IdentityModel is used to simplify the code.

var client = new HttpClient();
var tokenRequest = new ClientCredentialsTokenRequest
{
     Address = "https://YOURINSTANCE.irmciam.se/connect/token",
     ClientId = "THE_CLIENT_ID",
     ClientSecret = "THE_CLIENT_SECRET",
     Scope = "THE_SCOPES_REQUIRED_TO_CALL_THE_API"
};
                
var response = await client.RequestClientCredentialsTokenAsync(tokenRequest);
                
if (response.IsError) throw new Exception(response.Error);
                
var token = response.AccessToken;

Use the Access Token

After retrieving the access token it should be added in the Authrozation HTTP header on all calls to the API:

Authorization: Bearer THE_ACCESS_TOKEN

The token is typically valid for a while (in many scenarios 1 hour), so re-use the token in multiple calls instead of retrieving a new for each call. This is extra important when many calls are done, since this will otherwise cause unnecessary load on Authway.