예제 #1
0
        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));
        }
        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)));
        }
예제 #3
0
        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);
                }
            }
                );
        }