Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Client Credentials Authorization Flow in C# (Spotify API)
using System;
namespace authtest
{
class AccessToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public long expires_in { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
namespace authtest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Spotify API");
AccessToken token = GetToken().Result;
Console.WriteLine(String.Format("Access Token: {0}",token.access_token));
}
static async Task<AccessToken> GetToken()
{
Console.WriteLine("Getting Token");
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);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment