Skip to content

Instantly share code, notes, and snippets.

@lqdev
Last active January 5, 2021 17:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lqdev/5e82a5c856fcf0818e0b5e002deb0c28 to your computer and use it in GitHub Desktop.
Save lqdev/5e82a5c856fcf0818e0b5e002deb0c28 to your computer and use it in GitHub Desktop.
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);
}
}
}
}
@mologni
Copy link

mologni commented Mar 30, 2020

@shaiksaleem7

Change: private static async Task<string> GetToken()

To: private static async Task<AccessToken> GetToken()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment