public async Task <string> GetToken(ISpotifyTokenRequest req) { try { string access_token = ""; using (var http = new HttpClient()) { http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", req.ToAuthorization()); Dictionary <string, string> dict = new Dictionary <string, string>(); dict.Add("grant_type", req.GetGrantType()); FormUrlEncodedContent content = new FormUrlEncodedContent(dict); HttpResponseMessage request = await http.PostAsync(_config["Spotify:TokenURI"], content); Task <string> response = request.Content.ReadAsStringAsync(); if (response.IsCompleted) { resp = response.Result.JsonToObject <SpotifyTokenResponse>(); access_token = resp.access_token; } return(access_token); }; } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } }
/// <summary> /// Initializes a new instance based on the specified <paramref name="refreshToken"/>. /// </summary> /// <param name="clientId">The client ID.</param> /// <param name="clientSecret">The client secret.</param> /// <param name="refreshToken">The refresh token of the user.</param> /// <returns>The created instance of <see cref="Skybrud.Social.Spotify.SpotifyService" />.</returns> public static SpotifyService CreateFromRefreshToken(string clientId, string clientSecret, string refreshToken) { if (String.IsNullOrWhiteSpace(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (String.IsNullOrWhiteSpace(clientSecret)) { throw new ArgumentNullException(nameof(clientSecret)); } if (String.IsNullOrWhiteSpace(refreshToken)) { throw new ArgumentNullException(nameof(refreshToken)); } // Initialize a new OAuth client SpotifyOAuthClient client = new SpotifyOAuthClient(clientId, clientSecret); // Get an access token from the refresh token. SpotifyTokenResponse response = client.GetAccessTokenFromRefreshToken(refreshToken); // Update the OAuth client with the access token client.AccessToken = response.Body.AccessToken; // Initialize a new service instance return(new SpotifyService(client)); }
public IHttpActionResult Create(string code) { Session session = null; var client = new RestClient(Constants.Spotify.AccountsBaseApi); var request = new RestRequest("token", Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", $"client_id={Constants.Spotify.ClientId}&client_secret={Constants.Spotify.ClientSecret}&grant_type={grantType}&code={code}&redirect_uri={Constants.Spotify.RedirectUri}", ParameterType.RequestBody); IRestResponse response = client.Execute(request); if (response.IsSuccessful) { SpotifyTokenResponse responseBody = JsonConvert.DeserializeObject <SpotifyTokenResponse>(response.Content); if (responseBody.scope != null && responseBody.access_token != null) { SpotifyCredentials credentials = new SpotifyCredentials(responseBody.access_token, responseBody.refresh_token, new List <string>(responseBody.scope.Split(' '))); IPlayer player = new SpotifyPlayer(credentials); session = new Session(player); sessions.Add(session); } } return(session != null ? (IHttpActionResult)Ok(session) : NotFound()); }
public Token(SpotifyTokenResponse token) { this.AccessToken = token.accessToken; this.TokenType = token.tokenType; this.ExpiresIn = token.expiresIn; this.RefreshToken = token.refreshToken; this.CreateDate = token.CreationDate; }
private async void GetRefreshedToken(object source, ElapsedEventArgs e) { var tokenReqParams = CreateTokenReqParams(RequestType.Refresh); var resp = await SpotifyPost <SpotifyTokenResponse>(SpotifyApiUrls.Token, tokenReqParams); _lastTokenResponse = resp; }
public virtual async Task <IToken> GetToken() { if (this.tokenReturned) { return(this.token); } if (this.AuthHttpServer == null) { return(null); } this.AuthHttpServer.AuthorizationFinished += this.AuthHttpServer_AuthorizationFinished; await this.AuthHttpServer.Start().ConfigureAwait(false); this.Authorize(); bool shouldAbortAuthorization = false; while (this.authResponse == null && !shouldAbortAuthorization) { await Task.Delay(100).ConfigureAwait(false); shouldAbortAuthorization = await this.ShouldAbortAuthorization().ConfigureAwait(false); } if (this.authResponse == null && shouldAbortAuthorization) { this.AuthHttpServer.AuthorizationFinished -= this.AuthHttpServer_AuthorizationFinished; await this.AuthHttpServer.Stop().ConfigureAwait(false); return(null); } if (this.authResponse != null && this.authResponse.Error == null && !string.IsNullOrWhiteSpace(this.authResponse.Code)) { if (this.authResponse.State == this.State || string.IsNullOrWhiteSpace(this.authResponse.State) && string.IsNullOrWhiteSpace(this.State)) { HttpResponse httpResponse = new HttpResponse(256, 1024); SpotifyTokenResponse spotifyTokenResponse = new SpotifyTokenResponse(256, 32, 736); AuthorizationCodeFlow.GetAuthorizationToken(ref httpResponse, ref spotifyTokenResponse, this.authResponse.Code); if (httpResponse.status == (int)HttpStatusCode.OK) { spotifyTokenResponse.CreationDate = DateTime.Now; this.token = this.CreateToken(spotifyTokenResponse); this.tokenReturned = true; } else { // TODO: Handle HTTP status != OK logger.Debug("TODO: Handle HTTP status != OK"); } } } this.tokenReturned = true; return(this.token); }
public async Task StartTokenRequests(string code) { var resp = await GetInitialResponse(code); _lastTokenResponse = resp; _tokenRefreshTimer = new Timer((resp.ExpiresIn - 2) * 1000); _tokenRefreshTimer.Elapsed += GetRefreshedToken; _tokenRefreshTimer.Start(); }
protected override IToken CreateToken(SpotifyTokenResponse spotifyTokenResponse) { return(new Token { AccessToken = spotifyTokenResponse.accessToken, TokenType = spotifyTokenResponse.tokenType, ExpiresIn = spotifyTokenResponse.expiresIn, RefreshToken = spotifyTokenResponse.refreshToken, CreateDate = spotifyTokenResponse.CreationDate }); }
public static async Task <SpotifyTokenResponse> GetToken(string code, string uri) { var tokenResponse = new SpotifyTokenResponse(); //using (var client = new HttpClient()) //{ // client.DefaultRequestHeaders.Accept.Clear(); // client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // // HTTP POST // var request = new SpotifyTokenRequest() // { // client_id = ClientID, // client_secret = ClientSecret, // code = code, // grant_type = "authorization_code", // redirect_uri = uri // }; // HttpResponseMessage response = await client.PostAsJsonAsync(SpotifyToken, JsonConvert.SerializeObject(request)); // if (response.IsSuccessStatusCode) // { // tokenResponse = await response.Content.ReadAsAsync<SpotifyTokenResponse>(); // } //} var httpWebRequest = (HttpWebRequest)WebRequest.Create(SpotifyToken); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { var request = new SpotifyTokenRequest() { client_id = ClientID, client_secret = ClientSecret, code = code, grant_type = "authorization_code", redirect_uri = uri }; string json = JsonConvert.SerializeObject(request); streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); } //Token = tokenResponse.access_token; return(tokenResponse); }
public virtual async Task <IToken> GetToken() { if (this.tokenReturned) { return(this.token); } if (this.AuthHttpServer == null) { return(null); } this.AuthHttpServer.AuthorizationFinished += this.AuthHttpServer_AuthorizationFinished; await this.AuthHttpServer.Start(); AuthorizationCodeFlow.Authorize(this.Scopes, this.State, this.ShowDialog); while (this.authResponse == null) { await Task.Delay(100); } if (this.authResponse.Error == null && !string.IsNullOrWhiteSpace(this.authResponse.Code)) { if (this.authResponse.State == this.State) { HttpResponse httpResponse = new HttpResponse(256, 1024); SpotifyTokenResponse spotifyTokenResponse = new SpotifyTokenResponse(256, 32, 736); AuthorizationCodeFlow.GetAuthorizationToken(ref httpResponse, ref spotifyTokenResponse, this.authResponse.Code); if (httpResponse.status == (int)HttpStatusCode.OK) { spotifyTokenResponse.CreationDate = DateTime.Now; this.token = this.CreateToken(spotifyTokenResponse); this.tokenReturned = true; return(this.token); } } } this.tokenReturned = true; return(null); }
/// <summary> /// Exchanges the specified <paramref name="authorizationCode"/> for a refresh token and an access token. /// </summary> /// <param name="authorizationCode">The authorization code received from the Spotify OAuth dialog.</param> /// <returns>An instance of <see cref="SpotifyTokenResponse"/> representing the response.</returns> /// <see> /// <cref>https://developer.spotify.com/web-api/authorization-guide/</cref> /// </see> public SpotifyTokenResponse GetAccessTokenFromAuthorizationCode(string authorizationCode) { // Input validation if (String.IsNullOrWhiteSpace(authorizationCode)) { throw new ArgumentNullException(nameof(authorizationCode)); } if (String.IsNullOrWhiteSpace(ClientId)) { throw new PropertyNotSetException(nameof(ClientId)); } if (String.IsNullOrWhiteSpace(ClientSecret)) { throw new PropertyNotSetException(nameof(ClientSecret)); } if (String.IsNullOrWhiteSpace(RedirectUri)) { throw new PropertyNotSetException(nameof(RedirectUri)); } // Initialize the POST data IHttpPostData postData = new SocialHttpPostData(); postData.Add("grant_type", "authorization_code"); postData.Add("code", authorizationCode); postData.Add("redirect_uri", RedirectUri); postData.Add("client_id", ClientId); postData.Add("client_secret", ClientSecret); // Initialize the request SocialHttpRequest request = new SocialHttpRequest { Method = SocialHttpMethod.Post, Url = "https://accounts.spotify.com/api/token", PostData = postData }; // Make a call to the server SocialHttpResponse response = request.GetResponse(); // Parse the JSON response return(SpotifyTokenResponse.ParseResponse(response)); }
private async Task <string> GetAccessTokenAsync() { if (_oAuthToken != null && _oAuthToken.CalulatedExpirationTime > DateTime.Now) { return(_oAuthToken.AccessToken); } const string tokenEndpoint = "https://accounts.spotify.com/api/token"; var result = await tokenEndpoint .WithBasicAuth(_clientId, _clientSecret) .PostUrlEncodedAsync(new { grant_type = "client_credentials" }) .ReceiveJson <SpotifyTokenResponse>(); _oAuthToken = result; _oAuthToken.CalulatedExpirationTime = DateTime.Now.AddSeconds(result.ExpiresIn); return(_oAuthToken.AccessToken); }
public Task <IToken> RefreshToken([NotNull] IToken token) { IToken refreshedToken = null; HttpResponse httpResponse = new HttpResponse(256, 1024); SpotifyTokenResponse spotifyTokenResponse = new SpotifyTokenResponse(256, 32, 736); AuthorizationCodeFlow.RefreshAuthorizationToken(ref httpResponse, ref spotifyTokenResponse, token.RefreshToken); if (httpResponse.status == (int)HttpStatusCode.OK) { spotifyTokenResponse.CreationDate = DateTime.Now; refreshedToken = this.CreateToken(spotifyTokenResponse); } else { // TODO: Handle HTTP status != OK logger.Debug("TODO: Handle HTTP status != OK"); } return(Task.FromResult(refreshedToken)); }
public static extern void GetClientCredentialsToken( [In, Out] ref HttpResponse response, [In, Out] ref SpotifyTokenResponse tokenResponse);
public static extern void RefreshAuthorizationToken( [In, Out] ref HttpResponse response, [In, Out] ref SpotifyTokenResponse tokenResponse, [In][MarshalAs(UnmanagedType.LPStr)] string refreshToken);
protected abstract IToken CreateToken(SpotifyTokenResponse spotifyTokenResponse);
protected override IToken CreateToken(SpotifyTokenResponse spotifyTokenResponse) { return(new Token(spotifyTokenResponse)); }