Last active
January 5, 2021 17:33
-
-
Save lqdev/5e82a5c856fcf0818e0b5e002deb0c28 to your computer and use it in GitHub Desktop.
Client Credentials Authorization Flow in C# (Spotify API)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace authtest | |
{ | |
class AccessToken | |
{ | |
public string access_token { get; set; } | |
public string token_type { get; set; } | |
public long expires_in { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
@shaiksaleem7
Change: private static async Task
<string>
GetToken()To: private static async Task
<AccessToken>
GetToken()