Added method to RefreshToken for auth code flow

Fixed some includes
This commit is contained in:
Jonas Dellinger 2018-09-21 14:45:14 +02:00
parent a302694da8
commit e7f40474c2
3 changed files with 33 additions and 19 deletions

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -9,11 +10,8 @@ using SpotifyAPI.Web.Models;
using Unosquare.Labs.EmbedIO; using Unosquare.Labs.EmbedIO;
using Unosquare.Labs.EmbedIO.Constants; using Unosquare.Labs.EmbedIO.Constants;
using Unosquare.Labs.EmbedIO.Modules; using Unosquare.Labs.EmbedIO.Modules;
#if NETSTANDARD2_0 using Unosquare.Swan;
using System.Net.Http;
#endif
#if NET46 #if NET46
using System.Net.Http;
using HttpListenerContext = Unosquare.Net.HttpListenerContext; using HttpListenerContext = Unosquare.Net.HttpListenerContext;
#endif #endif
@ -45,12 +43,32 @@ namespace SpotifyAPI.Web.Auth
return ShouldRegisterNewApp() ? $"{RedirectUri}/start.html#{State}" : base.GetUri(); return ShouldRegisterNewApp() ? $"{RedirectUri}/start.html#{State}" : base.GetUri();
} }
protected override WebServer AdaptWebServer(WebServer webServer) => webServer.WithWebApiController<AuthorizationCodeAuthController>(); protected override WebServer AdaptWebServer(WebServer webServer)
{
return webServer.WithWebApiController<AuthorizationCodeAuthController>();
}
private string GetAuthHeader() => $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes(ClientId + ":" + SecretId))}";
public async Task<Token> RefreshToken(string refreshToken)
{
List<KeyValuePair<string, string>> args = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("grant_type", "refresh_token"),
new KeyValuePair<string, string>("refresh_token", refreshToken)
};
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", GetAuthHeader());
HttpContent content = new FormUrlEncodedContent(args);
HttpResponseMessage resp = await client.PostAsync("https://accounts.spotify.com/api/token", content);
string msg = await resp.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Token>(msg);
}
public async Task<Token> ExchangeCode(string code) public async Task<Token> ExchangeCode(string code)
{ {
string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes(ClientId + ":" + SecretId));
List<KeyValuePair<string, string>> args = new List<KeyValuePair<string, string>>() List<KeyValuePair<string, string>> args = new List<KeyValuePair<string, string>>()
{ {
new KeyValuePair<string, string>("grant_type", "authorization_code"), new KeyValuePair<string, string>("grant_type", "authorization_code"),
@ -59,7 +77,7 @@ namespace SpotifyAPI.Web.Auth
}; };
HttpClient client = new HttpClient(); HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Basic {auth}"); client.DefaultRequestHeaders.Add("Authorization", GetAuthHeader());
HttpContent content = new FormUrlEncodedContent(args); HttpContent content = new FormUrlEncodedContent(args);
HttpResponseMessage resp = await client.PostAsync("https://accounts.spotify.com/api/token", content); HttpResponseMessage resp = await client.PostAsync("https://accounts.spotify.com/api/token", content);

View File

@ -47,7 +47,7 @@ namespace SpotifyAPI.Web.Auth
_server = WebServer.Create(ServerUri, RoutingStrategy.Regex); _server = WebServer.Create(ServerUri, RoutingStrategy.Regex);
_server.RegisterModule(new WebApiModule()); _server.RegisterModule(new WebApiModule());
AdaptWebServer(_server); AdaptWebServer(_server);
_server.RegisterModule(new ResourceFilesModule(typeof(ImplictGrantAuth).Assembly, $"SpotifyAPI.Web.Auth.Resources.{_folder}")); _server.RegisterModule(new ResourceFilesModule(typeof(T).Assembly, $"SpotifyAPI.Web.Auth.Resources.{_folder}"));
#pragma warning disable 4014 #pragma warning disable 4014
_server.RunAsync(_serverSource.Token); _server.RunAsync(_serverSource.Token);
#pragma warning restore 4014 #pragma warning restore 4014

View File

@ -6,7 +6,7 @@ using SpotifyAPI.Web.Models;
namespace SpotifyAPI.Web.Example namespace SpotifyAPI.Web.Example
{ {
static class Program internal static class Program
{ {
private static string _clientId = ""; //""; private static string _clientId = ""; //"";
private static string _secretId = ""; //""; private static string _secretId = ""; //"";
@ -14,11 +14,11 @@ namespace SpotifyAPI.Web.Example
static void Main(string[] args) static void Main(string[] args)
{ {
_clientId = string.IsNullOrEmpty(_clientId) _clientId = string.IsNullOrEmpty(_clientId)
? System.Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_ID") ? Environment.GetEnvironmentVariable("SPOTIFY_CLIENT_ID")
: _clientId; : _clientId;
_secretId = string.IsNullOrEmpty(_secretId) _secretId = string.IsNullOrEmpty(_secretId)
? System.Environment.GetEnvironmentVariable("SPOTIFY_SECRET_ID") ? Environment.GetEnvironmentVariable("SPOTIFY_SECRET_ID")
: _secretId; : _secretId;
Console.WriteLine("####### Spotify API Example #######"); Console.WriteLine("####### Spotify API Example #######");
@ -34,10 +34,6 @@ namespace SpotifyAPI.Web.Example
auth.Start(); auth.Start();
auth.OpenBrowser(); auth.OpenBrowser();
/* ImplictGrantAuth auth = new ImplictGrantAuth("26d287105e31491889f3cd293d85bfea", "http://localhost:4002", "http://localhost:4002");
auth.Start();
auth.OpenBrowser();*/
Console.ReadLine(); Console.ReadLine();
auth.Stop(0); auth.Stop(0);
} }
@ -48,15 +44,15 @@ namespace SpotifyAPI.Web.Example
auth.Stop(); auth.Stop();
Token token = await auth.ExchangeCode(payload.Code); Token token = await auth.ExchangeCode(payload.Code);
SpotifyWebAPI api = new SpotifyWebAPI() SpotifyWebAPI api = new SpotifyWebAPI
{ {
AccessToken = token.AccessToken, AccessToken = token.AccessToken,
TokenType = token.TokenType TokenType = token.TokenType
}; };
PrintUsefulDate(api); PrintUsefulData(api);
} }
private static async void PrintUsefulDate(SpotifyWebAPI api) private static async void PrintUsefulData(SpotifyWebAPI api)
{ {
PrivateProfile profile = await api.GetPrivateProfileAsync(); PrivateProfile profile = await api.GetPrivateProfileAsync();
string name = string.IsNullOrEmpty(profile.DisplayName) ? profile.Id : profile.DisplayName; string name = string.IsNullOrEmpty(profile.DisplayName) ? profile.Id : profile.DisplayName;