1. 1. Getting Started
  2. 2. Create a new .NET Core Console Application
  3. 3. Add Dependencies
  4. 4. Access Token Model
  5. 5. Request Token
    1. 5.0.0.0.0.1. Sources

Client Credentials Authorization in C#

Getting Started

For this writeup, I’m going to use the Spotify API. Spotify API supports different authorization flows. In this writeup, I will be using the client credentials authorization flow. Generally this works for server-to-server authentication. Because this does not allow users the ability to provide their own credentials, there is no access to endpoints that contain user data.

Create a new .NET Core Console Application

1
dotnet new console -o authtest

Add Dependencies

1
dotnet add package Newtonsoft.Json --version 10.0.3

Access Token Model

When a request is made, it needs to be parsed. To better capture the data into a Plain Old CLR Object (POCO), a model can be created.

1
2
3
4
5
6
7
8
9
10
11
using System;

namespace authtest
{
class AccessToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public long expires_in { get; set; }
}
}

Request Token

In order to extract our token, an HTTP Request needs to be made to the Spotify API in order to get an access token. To do so, we can leverage the HTTPClient functionalities.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private static async Task<string> GetToken()
{
string clientId = "YOUR CLIENT ID";
string clientSecret = "YOUR CLIENT SECRET";
string credentials = String.Format("{0}:{1}",clientId,clientSecret);

using(var client = new HttpClient())
{
//Define Headers
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));

//Prepare Request Body
List<KeyValuePair<string,string>> requestData = new List<KeyValuePair<string,string>>();
requestData.Add(new KeyValuePair<string,string>("grant_type","client_credentials"));

FormUrlEncodedContent requestBody = new FormUrlEncodedContent(requestData);

//Request Token
var request = await client.PostAsync("https://accounts.spotify.com/api/token",requestBody);
var response = await request.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<AccessToken>(response);
}
}

We can then use this function in our main method to request the token.

1
2
3
4
5
6
static void Main(string[] args)
{
Console.WriteLine("Spotify API");
AccessToken token = GetToken().Result;
Console.WriteLine(String.Format("Access Token: {0}",token.access_token));
}

This should produce the following output

1
2
3
Spotify API
Getting Token
Access Token: "YOUR ACCESS TOKEN"

The token can now be used to make requests to the Spotify API.

Source Code can be found here Source Code

Sources

Spotify Authorization Guide