#pragma warning disable 1998
        public override async Task <CommandResult> ExecuteAsync(CancellationToken cancel)
        {
            string authUrl = AuthenticationService.GetWindowsLiveAuthenticationUrl();

            Console.WriteLine($"Go to following URL and authenticate: {authUrl}");
            Console.WriteLine("Paste the returned URL and press ENTER: ");

            string redirectUrl = Console.ReadLine();

            try
            {
                WindowsLiveResponse response = AuthenticationService
                                               .ParseWindowsLiveResponse(redirectUrl);

                AuthenticationService authService = new AuthenticationService(response);

                await authService.AuthenticateAsync();

                await authService.DumpToJsonFileAsync(TokenFilePath);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Authentication failed! {e.Message}");
                return(CommandResult.RuntimeFailure);
            }

            Console.WriteLine($"Authentication succeeded, tokens saved to {TokenFilePath}");
            return(CommandResult.Success);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            string responseUrl;
            string requestUrl = AuthenticationService.GetWindowsLiveAuthenticationUrl();

            if (args.Length < 1)
            {
                Console.WriteLine("1) Open following URL in your WebBrowser:\n\n{0}\n\n" +
                                  "2) Authenticate with your Microsoft Account\n" +
                                  "3) Paste returned URL from addressbar: \n", requestUrl);

                // Caveat: Console.ReadLine() is limited to 254 chars on Windows
                responseUrl = Console.ReadLine();
            }
            else
            {
                responseUrl = args[0];
            }

            WindowsLiveResponse response = AuthenticationService.ParseWindowsLiveResponse(responseUrl);

            AuthenticationService authenticator = new AuthenticationService(
                new AccessToken(response), new RefreshToken(response));

            bool success = authenticator.Authenticate();

            if (!success)
            {
                Console.WriteLine("Authentication failed!");
                return;
            }
            Console.WriteLine(authenticator.XToken);
            Console.WriteLine(authenticator.UserInformation);
        }
Exemplo n.º 3
0
        static void Authenticate(string url)
        {
            AuthenticationService auth;

            try
            {
                // Call requestUrl via WebWidget or manually and authenticate
                WindowsLiveResponse rep = AuthenticationService.ParseWindowsLiveResponse(url);
                (auth = new AuthenticationService(rep)).Authenticate();
            }
            catch (Exception e)
            {
                throw Shell.Log("Authentication failed, error: {0}", e, e.Message);
            }

            FileStream tokenOutputFile;

            try
            {
                using (tokenOutputFile = new FileStream(_tokenFilePath, FileMode.Create))
                    auth.DumpToFile(tokenOutputFile); // Save token to JSON
            }
            catch (Exception e)
            {
                throw Shell.Log("Failed to open token outputfile \'{0}\', error: {1}", e
                                , _tokenFilePath, e.Message);
            }
            _userHash = auth.XToken.UserInformation.Userhash;
            _xToken   = auth.XToken.Jwt;

            Shell.WriteLine(auth.XToken);
            Shell.WriteLine(auth.UserInformation);
            Shell.WriteLine("Storing tokens to file \'{0}\' on successful auth"
                            , tokenOutputFile.Name);
        }
        /// <summary>
        /// Authenticate to Xbox Live.
        /// First it refreshes the Windows Live token, then it authenticates to XASU and XSTS
        /// </summary>
        /// <returns>Returns true on success, false otherwise</returns>
        public async Task <bool> AuthenticateAsync()
        {
            try
            {
                logger.LogTrace("AuthenticateAsync() called");
                logger.LogTrace("AuthenticateAsync: Calling RefreshLiveTokenAsync");
                WindowsLiveResponse windowsLiveTokens = await RefreshLiveTokenAsync(RefreshToken);

                logger.LogTrace("AuthenticateAsync: Constructing AccessToken");
                AccessToken = new AccessToken(windowsLiveTokens);
                logger.LogTrace("AuthenticateAsync: Constructing RefreshToken");
                RefreshToken = new RefreshToken(windowsLiveTokens);
                logger.LogTrace("AuthenticateAsync: Calling AuthenticateXASUAsync");
                UserToken = await AuthenticateXASUAsync(AccessToken);

                logger.LogTrace("AuthenticateAsync: Calling AuthenticateXSTSAsync");
                XToken = await AuthenticateXSTSAsync(UserToken, DeviceToken, TitleToken);
            }
            catch (HttpRequestException ex)
            {
                logger.LogError(ex, "AuthenticateAsync failed due to HTTP error: {}", ex.Message);
                return(false);
            }

            logger.LogTrace("AuthenticateAsync: Setting UserInformation");
            UserInformation = XToken.UserInformation;
            return(true);
        }
        public void ParseWindowsLiveResponseSuccess()
        {
            string responseUrl = TestData["WindowsLiveRedirectionUrl.url"];

            System.DateTime     dateBeforeParsing = System.DateTime.Now;
            WindowsLiveResponse response          = AuthenticationService.ParseWindowsLiveResponse(responseUrl);

            Assert.IsNotNull(response);

            AccessToken  accessToken  = new AccessToken(response);
            RefreshToken refreshToken = new RefreshToken(response);

            Assert.IsFalse(accessToken.HasUserInformation);
            Assert.IsNull(accessToken.UserInformation);
            Assert.IsTrue(accessToken.Valid);
            Assert.AreEqual(accessToken.Jwt, "EwAAA+pvBAAUKods63Ys1fGlwiccIFJ+9u");
            Assert.GreaterOrEqual(accessToken.Issued, dateBeforeParsing);
            Assert.GreaterOrEqual(accessToken.Expires, accessToken.Issued);

            Assert.IsFalse(refreshToken.HasUserInformation);
            Assert.IsNull(refreshToken.UserInformation);
            Assert.IsTrue(refreshToken.Valid);
            Assert.AreEqual(refreshToken.Jwt, "MCdhvIzN1f!FoKyCigwGbM$$");
            Assert.GreaterOrEqual(refreshToken.Issued, dateBeforeParsing);
            Assert.GreaterOrEqual(refreshToken.Expires, refreshToken.Issued);

            Assert.Greater(refreshToken.Expires, accessToken.Expires);
        }
Exemplo n.º 6
0
        async Task RefreshWindowsLiveTokenAsync()
        {
            WindowsLiveResponse wlResponse = await AuthenticationService.RefreshLiveTokenAsync(RefreshToken);

            // Update Account
            Account = CreateAccountFromResponse(wlResponse);

            AccessToken  = new AccessToken(wlResponse);
            RefreshToken = new RefreshToken(wlResponse);
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            FileStream tokenOutputFile = null;
            string     responseUrl     = null;
            string     requestUrl      = AuthenticationService.GetWindowsLiveAuthenticationUrl();

            if (args.Length < 1)
            {
                Console.WriteLine("1) Open following URL in your WebBrowser:\n\n{0}\n\n" +
                                  "2) Authenticate with your Microsoft Account\n" +
                                  "3) Paste returned URL from addressbar: \n", requestUrl);
                return;
            }

            if (args.Length == 2)
            {
                string tokenOutputFilePath = args[1];
                try
                {
                    tokenOutputFile = new FileStream(tokenOutputFilePath, FileMode.Create);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to open token outputfile \'{0}\', error: {1}",
                                      tokenOutputFile, e.Message);
                    return;
                }
                Console.WriteLine("Storing tokens to file \'{0}\' on successful auth",
                                  tokenOutputFilePath);
            }

            responseUrl = args[0];

            WindowsLiveResponse response = AuthenticationService.ParseWindowsLiveResponse(responseUrl);

            AuthenticationService authenticator = new AuthenticationService(
                new AccessToken(response), new RefreshToken(response));

            bool success = authenticator.Authenticate();

            if (!success)
            {
                Console.WriteLine("Authentication failed!");
                return;
            }

            if (tokenOutputFile != null)
            {
                authenticator.DumpToFile(tokenOutputFile);
                tokenOutputFile.Close();
            }

            Console.WriteLine(authenticator.XToken);
            Console.WriteLine(authenticator.UserInformation);
        }
Exemplo n.º 8
0
        public bool Authenticate()
        {
            WindowsLiveResponse windowsLiveTokens = RefreshLiveToken(RefreshToken);

            AccessToken     = new AccessToken(windowsLiveTokens);
            RefreshToken    = new RefreshToken(windowsLiveTokens);
            UserToken       = AuthenticateXASU(AccessToken);
            XToken          = AuthenticateXSTS(UserToken, DeviceToken, TitleToken);
            UserInformation = XToken.UserInformation;
            return(true);
        }
        public void ParseValidRefreshToken()
        {
            string content = TestData["RefreshToken.json"];
            WindowsLiveResponse response = NewtonsoftJsonSerializer.Create(JsonNamingStrategy.SnakeCase)
                                           .Deserialize <WindowsLiveResponse>(content);

            Assert.AreEqual(response.TokenType, "bearer");
            Assert.AreEqual(response.ExpiresIn, 86400);
            Assert.AreEqual(response.Scope, "service::user.auth.xboxlive.com::MBI_SSL");
            Assert.AreEqual(response.AccessToken, "EWCAA/bdf+sd34ji234kasdf34asfs==");
            Assert.AreEqual(response.RefreshToken, "CuZ*4TX7!SAF33cW*kzdFLPRcz0DtU$$");
            Assert.AreEqual(response.UserId, "a42bdc501731723e");
        }
Exemplo n.º 10
0
        public static Xamarin.Auth.Account CreateAccountFromResponse(WindowsLiveResponse response)
        {
            var account = new Xamarin.Auth.Account();

            account.SetCreationDateTime(response.CreationTime);
            account.SetAccessTokenExpirationSeconds(response.ExpiresIn);
            account.SetAccessTokenJwt(response.AccessToken);
            account.SetRefreshTokenJwt(response.RefreshToken);
            account.SetTokenType(response.TokenType);
            account.SetScope(response.Scope);
            account.SetUserId(response.UserId);
            return(account);
        }
        public void ParseInvalidRefreshToken()
        {
            string content = TestData["InvalidData.json"];
            WindowsLiveResponse response = NewtonsoftJsonSerializer.Create(JsonNamingStrategy.SnakeCase)
                                           .Deserialize <WindowsLiveResponse>(content);

            Assert.AreEqual(response.ExpiresIn, 0);
            Assert.IsNull(response.TokenType);
            Assert.IsNull(response.Scope);
            Assert.IsNull(response.AccessToken);
            Assert.IsNull(response.RefreshToken);
            Assert.IsNull(response.UserId);
        }
        public async Task <bool> AuthenticateAsync()
        {
            WindowsLiveResponse windowsLiveTokens = await RefreshLiveTokenAsync(RefreshToken);

            AccessToken  = new AccessToken(windowsLiveTokens);
            RefreshToken = new RefreshToken(windowsLiveTokens);
            UserToken    = await AuthenticateXASUAsync(AccessToken);

            XToken = await AuthenticateXSTSAsync(UserToken, DeviceToken, TitleToken);

            UserInformation = XToken.UserInformation;
            return(true);
        }
Exemplo n.º 13
0
        static async Task <int> RunOAuth(OAuthOptions args)
        {
            Console.WriteLine(":: OAUTH ::");
            if (String.IsNullOrEmpty(args.ResponseUrl))
            {
                string requestUrl = AuthenticationService.GetWindowsLiveAuthenticationUrl();
                Console.WriteLine("1) Open following URL in your WebBrowser:\n\n{0}\n\n" +
                                  "2) Authenticate with your Microsoft Account\n" +
                                  "3) Execute application again with returned URL from addressbar as the argument\n", requestUrl);
            }
            else
            {
                try
                {
                    WindowsLiveResponse   response      = AuthenticationService.ParseWindowsLiveResponse(args.ResponseUrl);
                    AuthenticationService authenticator = new AuthenticationService(response);

                    Console.WriteLine("Attempting authentication with Xbox Live...");
                    bool success = await authenticator.AuthenticateAsync();

                    if (!success)
                    {
                        throw new Exception("Authentication failed!");
                    }
                    Console.WriteLine("Authentication succeeded");

                    if (!String.IsNullOrEmpty(args.TokenFilepath))
                    {
                        success = await authenticator.DumpToJsonFileAsync(args.TokenFilepath);

                        if (!success)
                        {
                            Console.WriteLine($"Failed to dump tokens to {args.TokenFilepath}");
                            return(2);
                        }
                        Console.WriteLine($"Tokens saved to {args.TokenFilepath}");
                    }
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Authentication failed! Error: " + exc.Message);
                    return(1);
                }
            }

            return(0);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Authenticates a Microsoft Account Identity with Windows Live
        /// </summary>
        /// <param name="windowsLiveAuthenticationServer">The URL of the custom Windows Live Authentication Server</param>
        /// <param name="identity">The email address of the Microsoft Account</param>
        /// <param name="identityPassword">The password of the Microsoft Account</param>
        /// <param name="identityTwoFactorCode">If the Microsoft Account has two factor authentication, put the code from the authenticator app here.</param>
        public static async Task <WindowsLiveAuthenticateResponse> AuthenticateWindowsLiveAsync(string windowsLiveAuthenticationServer, string identity, string identityPassword, string identityTwoFactorCode = null)
        {
            // Call remote api to get tokens
            var httpClient = new HttpClient();
            var response   = await httpClient.PostAsync(windowsLiveAuthenticationServer,
                                                        new StringContent(JsonConvert.SerializeObject(new WindowsLiveRequest
            {
                Identity = identity,
                IdentityPassword = identityPassword,
                IdentityTwoFactorCode = identityTwoFactorCode
            }), Encoding.UTF8, "application/json"));

            if (!response.IsSuccessStatusCode)
            {
                throw new FriendlyException("Invalid HTTP response from the Windows Live Authentication Server");
            }

            var stringResponse = await response.Content.ReadAsStringAsync();

            WindowsLiveResponse <WindowsLiveAuthenticateResponse> parsedResponse = null;

            try
            {
                parsedResponse = JsonConvert.DeserializeObject <WindowsLiveResponse <WindowsLiveAuthenticateResponse> >(stringResponse);
            }
            catch (Exception ex)
            {
                throw new FriendlyException("Invalid response from Windows Live Authentication Server", ex);
            }

            if (parsedResponse.Error != null)
            {
                throw new FriendlyException(parsedResponse.Error.ErrorDescription);
            }

            if (parsedResponse.Result == null || parsedResponse.Result.AccessToken == null || parsedResponse.Result.RefreshToken == null)
            {
                throw new FriendlyException("Invalid response from Windows Live Authentication Server");
            }

            return(parsedResponse.Result);
        }
Exemplo n.º 15
0
        static void Main()
        {
            AllocConsole();

            Console.Write("tokenFilePath: ");
            string tokenFilePath = Console.ReadLine();

            AuthenticationService auth;

            if (!File.Exists(tokenFilePath))
            {
                Shell.WriteLine("Warning: '{0}' file not found.\n", tokenFilePath);

                string reqURL = AuthenticationService.GetWindowsLiveAuthenticationUrl();

                Console.WriteLine("1) Open following URL in your WebBrowser:\n\n{0}\n\n" +
                                  "2) Authenticate with your Microsoft Account\n" +
                                  "3) Paste returned URL from addressbar: \n", reqURL);

                // Call requestUrl via WebWidget or manually and authenticate

                try
                {
                    string url = Console.ReadLine();
                    WindowsLiveResponse rep = AuthenticationService.ParseWindowsLiveResponse(url);
                    auth = new AuthenticationService(rep);

                    auth.Authenticate();
                }
                catch (Exception e)
                {
                    Shell.WriteLine($"Error: Authentication failed, error: {e.Message}");
                    Shell.PressAnyKeyToContinue();
                    return;
                }

                Console.WriteLine(auth.XToken);
                Console.WriteLine(auth.UserInformation);

                // Save token to JSON

                FileStream tokenOutputFile = null;
                try
                {
                    tokenOutputFile = new FileStream(tokenFilePath, FileMode.Create);
                }
                catch (Exception e)
                {
                    Shell.WriteLine("Error: Failed to open token outputfile \'{0}\', error: {1}",
                                    tokenOutputFile, e.Message);
                    Shell.PressAnyKeyToContinue();
                    return;
                }
                auth.DumpToFile(tokenOutputFile);
                tokenOutputFile.Close();

                Console.WriteLine("Storing tokens to file \'{0}\' on successful auth",
                                  tokenOutputFile.Name);
            }
            else
            {
                // Load token from JSON

                FileStream fs = new FileStream(tokenFilePath, FileMode.Open);
                auth = AuthenticationService.LoadFromFile(fs);
                try
                {
                    auth.Authenticate();
                }
                catch (Exception e)
                {
                    Shell.WriteLine($"Error: Failed to refresh XBL tokens, error: {e.Message}");
                    Shell.PressAnyKeyToContinue();
                    return;
                }
                fs.Close();
            }

            UserHash = auth.XToken.UserInformation.Userhash;
            XToken   = auth.XToken.Jwt;

            Discover().Wait();

            Console.Write("Input IP Address or hostname: ");
            string addressOrHostname = Console.ReadLine();

            Console.WriteLine($"Connecting to {addressOrHostname}...");
            SmartGlassClient client;

            try
            {
                Task <SmartGlassClient> connect = SmartGlassClient.ConnectAsync(
                    addressOrHostname, UserHash, XToken);

                // 如果Task失败了GetAwaiter()会直接抛出异常,而Task.Wait()会抛出AggregateException
                client = connect.GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                if (e is SmartGlassException)
                {
                    Shell.WriteLine($"Error: Failed to connect: {e.Message}");
                }
                else if (e is TimeoutException)
                {
                    Shell.WriteLine($"Error: Timeout while connecting: {e.Message}");
                }
                else
                {
                    Shell.WriteLine($"Error: {e}");
                }

                Shell.PressAnyKeyToContinue();
                return;
            }

            // Get general gamestream configuration
            GamestreamConfiguration config = GamestreamConfiguration.GetStandardConfig();
            // Modify standard config, if desired

            GamestreamSession session = client.BroadcastChannel.StartGamestreamAsync(config)
                                        .GetAwaiter().GetResult();

            Console.WriteLine($"Connecting to NANO // TCP: {session.TcpPort}, UDP: {session.UdpPort}");

            Console.WriteLine($"Running protocol init...");
            Nano = new NanoClient(addressOrHostname, session);
            try
            {
                // General Handshaking & Opening channels
                Nano.InitializeProtocolAsync().Wait();

                // Start Controller input channel
                Nano.OpenInputChannelAsync(1280, 720).Wait();

                //IConsumer consumer = /* initialize consumer */;
                //nano.AddConsumer(consumer);

                // Start consumer, if necessary
                //consumer.Start();

                // Audio & Video client handshaking
                // Sets desired AV formats
                Console.WriteLine("Initializing AV stream (handshaking)...");

                AudioFormat = Nano.AudioFormats[0];
                VideoFormat = Nano.VideoFormats[0];

                Nano.InitializeStreamAsync(AudioFormat, VideoFormat).Wait();

                // Start ChatAudio channel
                // TODO: Send opus audio chat samples to console
                ChatAudioFormat = new AudioFormat(1, 24000, AudioCodec.Opus);
                Nano.OpenChatAudioChannelAsync(ChatAudioFormat).Wait();

                // Tell console to start sending AV frames
                Console.WriteLine("Starting stream...");

                Nano.StartStreamAsync().Wait();

                Shell.WriteLine("Note: Stream is running");
            }
            catch (Exception e)
            {
                Shell.WriteLine($"Error: Failed to init Nano, error: {e}");
                Shell.PressAnyKeyToContinue();
                return;
            }

            // Run a mainloop, to gather controller input events or similar

            FreeConsole();

            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Xstream());

            // finally (dirty)
            Process.GetCurrentProcess().Kill();
        }
 public AuthenticationService(WindowsLiveResponse wlResponse)
 {
     AccessToken  = new AccessToken(wlResponse);
     RefreshToken = new RefreshToken(wlResponse);
 }
 /// <summary>
 /// Initializes a new instance of AuthenticationService via WindowsLiveResponse.
 /// </summary>
 /// <param name="wlResponse">
 /// Windows Live response, either constructed from redirect URI
 /// or by refreshing token
 /// </param>
 public AuthenticationService(WindowsLiveResponse wlResponse)
 {
     logger.LogTrace("AuthenticationService(WindowsLiveResponse wlResponse) ctor called");
     AccessToken  = new AccessToken(wlResponse);
     RefreshToken = new RefreshToken(wlResponse);
 }