Help us enhance your Sophos Community experience. Share your thoughts in our Sophos Community survey.

Sophos Central API Token Request

Hi everyone,

I'm planning to add some Sophos API functions into an in-house application written in C#. At the moment I'm just working on a scratch app so that I can test code for authenticating, getting a token etc. without affecting live code, but I'm struggling to get a token from the API. The code so far looks like this:

                try
                {
                    using (var client = new HttpClient())
                    {
                        var body = $"grant_type=client_credentials&client_id={SophosClientID}&client_secret={SophosClientSecret}&scope=token";
                        using (var msg = new HttpRequestMessage
                        {
                            RequestUri = new Uri(SophosAPIUrl), // https://id.sophos.com/api/v2/oauth2/token
                            Method = HttpMethod.Post,
                            Content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded")
                        })
                        {
                            var result = client.SendAsync(msg).GetAwaiter().GetResult();
                            if(result != null)
                            {
                                var token = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                                UpdateTextBox(token);
                            }
                            else
                            {
                                UpdateTextBox("Result was null");
                            }
                        }
                    }
                }
                catch(Exception ex)
                {
                    UpdateTextBox($"Process failed: {ex.Message}");
                }

The values for SophosClientID and SophosClientSecret are from the API credentials page. I've test with CURL and it works OK but the code above always returns a "Bad Request" error. I'd be grateful for any advice/tips on how to get this working.

Andy