public CustomToken RefreshToken(string refreshToken, string clientSecret) { AutorizationCodeAuth auth = new AutorizationCodeAuth() { ClientId = Constants.ClientId, State = Constants.StateKey }; Token response; CustomToken result = null; try { response = auth.RefreshToken(refreshToken, clientSecret); result = response.ToCustomToken(); if (result != null) { result.RefreshToken = refreshToken; } } catch (Exception ex) { } return(result); }
private static SpotifyWebAPI GetWebClient(SpotifyUser oSpotifyUser) { AutorizationCodeAuth oAuth = new AutorizationCodeAuth() { ClientId = _ClientPublic, RedirectUri = _RedirectUrl, Scope = Scope.UserReadPrivate | Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.UserFollowRead }; //oAuth.StartHttpServer();//Not sure if this is needed or not but what the hell why not! if (oSpotifyUser.AccessToken.AccessExpired)//The user has authorized us and was tokenized but the temp access token has expired { Token oToken = oAuth.RefreshToken(oSpotifyUser.RefreshToken.Code, _ClientPrivate); if (oToken.Error == null) { oSpotifyUser.UpdateUserWithToken(oToken); } } //oAuth.StopHttpServer(); SpotifyWebAPI oWebClient = new SpotifyWebAPI() { AccessToken = oSpotifyUser.AccessToken.Code, TokenType = oSpotifyUser.AccessToken.TokenType, UseAuth = true }; return(oWebClient); }
private static void OldWay() { //Create the auth object auth = new AutorizationCodeAuth() { //Your client Id ClientId = "4ba8934628a54571b57ed84de51d1825", //Set this to localhost if you want to use the built-in HTTP Server RedirectUri = "http://localhost:8000", //How many permissions we need? Scope = Scope.UserReadPrivate | Scope.PlaylistModifyPublic | Scope.PlaylistModifyPrivate, ShowDialog = true }; //This will be called, if the user cancled/accept the auth-request auth.OnResponseReceivedEvent += auth_OnResponseReceivedEvent; //a local HTTP Server will be started (Needed for the response) auth.StartHttpServer(8000); //This will open the spotify auth-page. The user can decline/accept the request try { auth.DoAuth(); Thread.Sleep(60000); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } auth.StopHttpServer(); Console.WriteLine("Too long, didnt respond, exiting now..."); }
public RockolappScreenData GetCurrentTrack(string spotifyUserId) { string token; var user = dataAccess.GetUser(spotifyUserId); var spotify = new SpotifyWebAPI() { TokenType = "Bearer", AccessToken = user.Token, UseAuth = true }; PlaybackContext context = spotify.GetPlayingTrack(); if (context.HasError() && context.Error.Status == 401) { AutorizationCodeAuth auth = new AutorizationCodeAuth(); //Datos de mi aplicacion Rocolapp auth.ClientId = DataAccess.GetRocolappData().ClientId; auth.RedirectUri = DataAccess.GetRocolappData().RedirectUri; string clientSecret = DataAccess.GetRocolappData().ClientSecret; Token newToken = auth.RefreshToken(user.RefreshToken, DataAccess.GetRocolappData().ClientSecret); dataAccess.UpdateToken(user.Id.ToString(), newToken.AccessToken); token = newToken.AccessToken; var withRefreshedToken = new SpotifyWebAPI() { TokenType = "Bearer", AccessToken = newToken.AccessToken, UseAuth = true }; context = withRefreshedToken.GetPlayingTrack(); } RockolappScreenData screenData = new RockolappScreenData(); try { screenData.TrackName = context.Item.Name; screenData.Artist = context.Item.Artists.First().Name; screenData.Duration = context.Item.DurationMs; screenData.LapsedTime = context.ProgressMs; screenData.ImageUrl = context.Item.Album.Images.First().Url; } catch (Exception) { } return(screenData); }
private Token RefreshToken(string refreshToken, string clientSecret) { AutorizationCodeAuth auth = new AutorizationCodeAuth() { ClientId = Constants.ClientId, State = Constants.StateKey }; return(auth.RefreshToken(refreshToken, clientSecret)); }
public static Token CreateNewToken(string refreshToken, string userId) { AutorizationCodeAuth auth = new AutorizationCodeAuth(); auth.ClientId = DataAccess.GetRocolappData().ClientId; auth.RedirectUri = DataAccess.GetRocolappData().RedirectUri; string clientSecret = DataAccess.GetRocolappData().ClientSecret; Token newToken = auth.RefreshToken(refreshToken, DataAccess.GetRocolappData().ClientSecret); return(newToken); }
public Window1() { InitializeComponent(); auth = new AutorizationCodeAuth() { ShowDialog = false, Scope = Scope.UserReadRecentlyPlayed | Scope.UserReadPrivate | Scope.UserReadEmail | Scope.UserReadBirthdate | Scope.UserLibraryRead | Scope.PlaylistReadPrivate, ClientId = SpotifyLogin.GetClient_Id, RedirectUri = SpotifyLogin.GetRedirect_Uri }; auth.OnResponseReceivedEvent += Auth_OnResponseReceivedEvent; }
private void OnLoginClick(object sender, RoutedEventArgs e) { //Create the auth object auth = new AutorizationCodeAuth { ClientId = Configuration.Comms.ClientId, RedirectUri = "http://localhost:8888", Scope = (Scope)0x1FFFF, }; auth.OnResponseReceivedEvent += OnAuthResponseReceived; auth.StartHttpServer(8888); auth.DoAuth(); }
public AuthHelper(Configuration config) { this.config = config; auth = new AutorizationCodeAuth { ClientId = config.Comms.ClientId, RedirectUri = "http://localhost:8888", Scope = (Scope)0x1FFFF, }; auth.OnResponseReceivedEvent += OnAuthResponseReceived; tokenRefreshTimer = new Timer(OnTokenRefreshTick); }
public void Authenticate() { AutorizationCodeAuth authentication = new AutorizationCodeAuth { RedirectUri = new UriBuilder("http://127.0.0.1") { Port = 7476 }.Uri.OriginalString.TrimEnd('/'), ClientId = _clientId, Scope = _scope, State = "XSS" }; // Try refreshing var token = authentication.RefreshToken(Properties.Settings.Default.RefreshToken, _clientSecret); if (token.Error == null) { WebAPI = ApiFromToken(token); return; } AutoResetEvent authenticationWaitFlag = new AutoResetEvent(false); WebAPI = null; authentication.OnResponseReceivedEvent += (response) => { WebAPI = HandleSpotifyResponse(response, authentication); authenticationWaitFlag.Set(); }; try { authentication.StartHttpServer(7476); authentication.DoAuth(); authenticationWaitFlag.WaitOne(TimeSpan.FromSeconds(_timeout)); if (WebAPI == null) { throw new TimeoutException($"No valid response received for the last {_timeout} seconds"); } } finally { authentication.StopHttpServer(); } }
public void RequestAuth(AutorizationCodeAuth.OnResponseReceived codeReceiveCallback) { if (AuthRequesting) { return; } AuthRequesting = true; AutorizationCodeAuth auth = new AutorizationCodeAuth(); auth.ClientId = ClientId; auth.RedirectUri = RedirUri; auth.Scope = Scope; auth.OnResponseReceivedEvent += response => { AuthRequesting = false; auth.StopHttpServer(); codeReceiveCallback.Invoke(response); }; auth.StartHttpServer(RedirPort); auth.DoAuth(); int ms = 0; while (ms < 30000) { if (!AuthRequesting) { break; } Thread.Sleep(100); ms += 100; } if (AuthRequesting) { auth.StopHttpServer(); AuthRequesting = false; } }
private static void Main() { using (var sr = new StreamReader("data/clientData.txt")) { _auth = new AutorizationCodeAuth() { ClientId = sr.ReadLine(), RedirectUri = "http://localhost", Scope = Scope.UserReadPrivate, }; _auth.StartHttpServer(); _clientSecret = sr.ReadLine(); _auth.OnResponseReceivedEvent += _callback; _auth.DoAuth(); } Console.ReadLine(); }
public void Run() { _auth = new AutorizationCodeAuth() { //Your client Id ClientId = "29876bdcb6384fc287e37ae01873058c", //Set this to localhost if you want to use the built-in HTTP Server RedirectUri = "http://localhost:7777/", //How many permissions we need? Scope = Scope.UserReadPrivate, }; //This will be called, if the user cancled/accept the auth-request _auth.OnResponseReceivedEvent += Auth_OnResponseReceivedEvent; //a local HTTP Server will be started (Needed for the response) _auth.StartHttpServer(7777); //This will open the spotify auth-page. The user can decline/accept the request _auth.DoAuth(); }
public Task <SpotifyWebAPI> GetWebApi() { var authentication = new AutorizationCodeAuth { RedirectUri = $"{_redirectUrl}:{_listeningPort}", ClientId = _clientId, Scope = _scope, State = _xss }; AutoResetEvent authenticationWaitFlag = new AutoResetEvent(false); SpotifyWebAPI spotifyWebApi = null; authentication.OnResponseReceivedEvent += (response) => { var state = response.State; var token = authentication.ExchangeAuthCode(response.Code, _clientSecret); spotifyWebApi = HandleSpotifyResponse(state, token); authenticationWaitFlag.Set(); }; try { authentication.StartHttpServer(_listeningPort); authentication.DoAuth(); authenticationWaitFlag.WaitOne(_timeout); if (spotifyWebApi == null) { throw new TimeoutException($"No valid response received for the last {_timeout.TotalSeconds} seconds"); } } finally { authentication.StopHttpServer(); } return(Task.FromResult(spotifyWebApi)); }
static SpotifyCommands() { Auth = new AutorizationCodeAuth { ClientId = Config.GetDefault("spotify/auth/clientId", "", "credentials"), RedirectUri = "http://localhost", Scope = Scope.UserReadPrivate }; _refreshToken(); Spotify = new SpotifyWebAPI { AccessToken = _token.AccessToken, TokenType = _token.TokenType, UseAuth = true }; Log.Info(Tag, "Spotify API setup done."); }
// GET: MainPage public ActionResult Main(string code) { AutorizationCodeAuth auth = new AutorizationCodeAuth(); RocolappUser rocolapUser; //Datos de mi aplicacion Rocolapp auth.ClientId = DataAccess.GetRocolappData().ClientId; auth.RedirectUri = DataAccess.GetRocolappData().RedirectUri; string clientSecret = DataAccess.GetRocolappData().ClientSecret; Token token = auth.ExchangeAuthCode(code, clientSecret); PrivateProfile privateProfile = GetUserProfile(token.AccessToken); var existence = CheckIfUserExists(privateProfile.Id); if (existence) { var user = GetUser(privateProfile.Id); rocolapUser = new RocolappUser() { Id = user.Id, SpotifyId = user.SpotifyId, Token = user.Token, RefreshToken = user.RefreshToken, PlaylistId = user.PlaylistId, Place = user.Place }; } else { FullPlaylist playList = CreatePlayList(privateProfile.Id, token.AccessToken); int ok = CreateUser(token.AccessToken, token.RefreshToken, privateProfile.Id, playList.Id); rocolapUser = new RocolappUser() { Id = ok, SpotifyId = privateProfile.Id, Token = token.AccessToken, RefreshToken = token.RefreshToken, PlaylistId = playList.Id }; } ViewData["pubUser"] = rocolapUser; return(View()); }
public ActionResult Index(string code = null) { AutorizationCodeAuth auth = new AutorizationCodeAuth { ClientId = Constants.ClientId, RedirectUri = Constants.RedirectUri, State = Constants.StateKey }; Token token = auth.ExchangeAuthCode(code, Constants.ClientSecret); _tokenService.SetToken(token.AccessToken, token.RefreshToken, token.ExpiresIn, TokenCredentialType.Auth); _sessionService.SetToken(token.ToCustomToken(TokenCredentialType.Auth)); bool chromeToken = _sessionService.getSession <bool>("ChromeToken"); if (chromeToken) { _sessionService.DeleteSession("ChromeToken"); return(Redirect(string.Format("~/?access_token={0}&refresh_token={1}&expires_in={2}", token.AccessToken, token.RefreshToken, token.ExpiresIn))); } if (_sessionService.getSession <bool>("fromIframe")) { _sessionService.DeleteSession("fromIframe"); return(RedirectToAction("CloseIframe", "Authorize")); } var returnUrl = _sessionService.GetReturnUrl(); if (returnUrl != null && !string.IsNullOrEmpty(returnUrl)) { if (!returnUrl.Contains(Url.RouteUrl("Authorize"))) { return(Redirect(returnUrl)); } } return(Redirect("~/")); }
public async Task <SearchItem> SearchTrack(string query, string tk) { RoclappData data = DataAccess.GetRocolappData(); RocolappUser user = GetUserbyRocolappId(tk); var spotify = new SpotifyWebAPI() { TokenType = "Bearer", AccessToken = user.Token, UseAuth = true }; SearchItem searchItem = spotify.SearchItems(query, SearchType.Track); if (searchItem.Error != null && searchItem.Error.Status == 401) { AutorizationCodeAuth auth = new AutorizationCodeAuth(); //Datos de mi aplicacion Rocolapp auth.ClientId = DataAccess.GetRocolappData().ClientId; auth.RedirectUri = DataAccess.GetRocolappData().RedirectUri; string clientSecret = DataAccess.GetRocolappData().ClientSecret; Token token = auth.RefreshToken(user.RefreshToken, DataAccess.GetRocolappData().ClientSecret); UpdateToken(user.Id.ToString(), token.AccessToken); var withRefreshedToken = new SpotifyWebAPI() { TokenType = "Bearer", AccessToken = token.AccessToken, UseAuth = true }; searchItem = withRefreshedToken.SearchItems(query, SearchType.Track); } return(searchItem); }
private SpotifyWebAPI HandleSpotifyResponse(AutorizationCodeAuthResponse response, AutorizationCodeAuth authentication) { if (response.State != "XSS") { throw new SpotifyWebApiException($"Wrong state '{response.State}' received."); } if (response.Error != null) { throw new SpotifyWebApiException($"Error: {response.Error}"); } var code = response.Code; var token = authentication.ExchangeAuthCode(code, _clientSecret); Properties.Settings.Default.RefreshToken = token.RefreshToken; Properties.Settings.Default.Save(); return(ApiFromToken(token)); }
/// <summary> /// /// </summary> private void DoAuth() { //Create the auth object auth = new AutorizationCodeAuth() { //Your client Id ClientId = "ce833ef1272046489c5cb86af277d9c0", //Set this to localhost if you want to use the built-in HTTP Server RedirectUri = "http://localhost", //RedirectUri = "http://treaiapi20170628103254.azurewebsites.net", //How many permissions we need? Scope = Scope.All }; //This will be called, if the user cancled/accept the auth-request auth.OnResponseReceivedEvent += auth_OnResponseReceivedEvent; //a local HTTP Server will be started (Needed for the response) auth.StartHttpServer(); //This will open the spotify auth-page. The user can decline/accept the request auth.DoAuth(); Thread.Sleep(5000); //auth.StopHttpServer(); Console.WriteLine("Too long, didnt respond, exiting now..."); }
public static SpotifyWebAPI GetInstanceAuth() { auth = new AutorizationCodeAuth() { //Your client Id spotifyClientID = MYSPOTIFY_CLIENTID, //Set this to localhost if you want to use the built-in HTTP Server RedirectUri = "http://localhost:8888", //How many permissions we need? Scope = Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate | Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic | Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.UserFollowRead | Scope.UserReadBirthdate | Scope.UserTopRead | Scope.PlaylistReadCollaborative | Scope.UserReadRecentlyPlayed | Scope.UserReadPlaybackState | Scope.UserModifyPlaybackState, }; //This will be called, if the user cancled/accept the auth-request auth.OnResponseReceivedEvent += auth_OnResponseReceivedEvent; //a local HTTP Server will be started (Needed for the response) auth.StartHttpServer(); //This will open the spotify auth-page. The user can decline/accept the request auth.DoAuth(); Thread.Sleep(10000); return(SPOTIFY_INST); }
private static void Authorize(CommandLineApplication command) { var clientIdOption = command.Option("-c|--clientId <clientId>", "The application client id", CommandOptionType.SingleValue); var clientSecretOption = command.Option("-k|--clientSecret <clientSecret>", "The application client secret", CommandOptionType.SingleValue); var scopeOption = command.Option("-s|--scope <scope>", "The application client secret", CommandOptionType.MultipleValue); var outputOption = command.Option("-o|--output <path>", "Path to output token as json", CommandOptionType.SingleValue); var browserPathOption = command.Option("-b|--browser <path>", "Path to the browser to start", CommandOptionType.SingleValue); command.OnExecute( () => { TaskCompletionSource <string> tcs = new TaskCompletionSource <string>(); Scope scope = scopeOption.Values .Select(v => Enum.Parse <Scope>(v)) .Aggregate(new Scope(), (a, s) => a | s); var auth = new AutorizationCodeAuth() { ClientId = clientIdOption.Value(), RedirectUri = "http://localhost", Scope = scope, ShowDialog = true, OpenUriAction = uri => Process.Start(new ProcessStartInfo { FileName = browserPathOption.Value(), Arguments = uri }) }; auth.OnResponseReceivedEvent += response => { Token token = auth.ExchangeAuthCode(response.Code, clientSecretOption.Value()); string json = JsonConvert.SerializeObject(token); tcs.SetResult(json); }; try { try { auth.StartHttpServer(); auth.DoAuth(); Task.WaitAll(new[] { tcs.Task }, TimeSpan.FromSeconds(30)); using (var stream = File.OpenWrite(outputOption.Value())) { using (var writer = new StreamWriter(stream)) { writer.Write(tcs.Task.Result); } } Console.WriteLine($"Successfully wrote token to '{outputOption.Value()}'"); return(0); } finally { auth.StopHttpServer(); } } catch (Exception e) { Console.WriteLine($"Failed to retrieve token: '{e.Message}'"); return(-1); } } ); }
public void AddTrackToPlayList([FromBody] Track track) { RoclappData data = DataAccess.GetRocolappData(); string token; RocolappUser user = GetUserbyRocolappId(track.Token); token = user.Token; var spotify = new SpotifyWebAPI() { TokenType = "Bearer", AccessToken = user.Token, UseAuth = true, }; //Agregar la posibilidad de que se aparezca la letra de la cancion string trackPrefix = "spotify:track:"; ErrorResponse response = spotify.AddPlaylistTrack(user.SpotifyId, user.PlaylistId, trackPrefix + track.TrackId); if (response.HasError() && response.Error.Status == 401) { AutorizationCodeAuth auth = new AutorizationCodeAuth(); //Datos de mi aplicacion Rocolapp auth.ClientId = DataAccess.GetRocolappData().ClientId; auth.RedirectUri = DataAccess.GetRocolappData().RedirectUri; string clientSecret = DataAccess.GetRocolappData().ClientSecret; Token newToken = auth.RefreshToken(user.RefreshToken, DataAccess.GetRocolappData().ClientSecret); UpdateToken(user.Id.ToString(), newToken.AccessToken); token = newToken.AccessToken; var withRefreshedToken = new SpotifyWebAPI() { TokenType = "Bearer", AccessToken = newToken.AccessToken, UseAuth = true }; response = withRefreshedToken.AddPlaylistTrack(user.SpotifyId, user.PlaylistId, trackPrefix + track.TrackId); } PlaybackContext context = GetCurrentPlayBack(token); if (context != null && !context.IsPlaying) { try { ResumePlayback(token); } catch (Exception) { throw; } } }
public RedirectResult Authorized(string code, string error, string state) { if (error != null) { throw new Exception(error); } AutorizationCodeAuth oAutorizationCodeAuth = new AutorizationCodeAuth() { //Your client Id ClientId = this._oSCCManager.SCC_PUBLIC_ID, //Set this to localhost if you want to use the built-in HTTP Server RedirectUri = this._oSCCManager.RedirectUrl, //How many permissions we need? Scope = Scope.UserReadPrivate | Scope.UserReadPrivate | Scope.PlaylistReadPrivate | Scope.UserLibraryRead | Scope.UserReadPrivate | Scope.UserFollowRead }; Token oToken; oToken = oAutorizationCodeAuth.ExchangeAuthCode(code, this._oSCCManager.SCC_PRIVATE_ID); //oToken = oAutorizationCodeAuth.RefreshToken(response.Code, SCC_PRIVATE_ID); SpotifyWebAPI oSpotifyWebApi = new SpotifyWebAPI() { AccessToken = oToken.AccessToken, TokenType = oToken.TokenType, UseAuth = true }; PrivateProfile oPrivateProfile = oSpotifyWebApi.GetPrivateProfile(); SpotifyUser oSpotifyUser = this._oSCCManager.AddSpotifyUser(oPrivateProfile, code, oToken); // ViewBag.RedirectUrl = string.Format("/SpotifyChangeControl/Change/Index?UserGuid={0}&SessionGuid={1}", oSpotifyUser.UserGuid, oSpotifyUser.SessionGuid); if (!this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("UserGuid")) { HttpCookie hcUserGuid = new HttpCookie("UserGuid"); hcUserGuid.Value = oSpotifyUser.UserGuid; this.ControllerContext.HttpContext.Response.Cookies.Add(hcUserGuid); this.ControllerContext.HttpContext.Response.Cookies.Add(hcUserGuid); } else { this.ControllerContext.HttpContext.Request.Cookies.Get("UserGuid").Value = oSpotifyUser.UserGuid; } if (!this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("SessionGuid")) { HttpCookie hcSessionGuid = new HttpCookie("SessionGuid"); hcSessionGuid.Value = oSpotifyUser.SessionGuid; this.ControllerContext.HttpContext.Response.Cookies.Add(hcSessionGuid); } else { this.ControllerContext.HttpContext.Request.Cookies.Get("SessionGuid").Value = oSpotifyUser.SessionGuid; } return(new RedirectResult(string.Format("/SpotifyChangeControl/Change/Index", oSpotifyUser.UserGuid, oSpotifyUser.SessionGuid))); }