Exemplo n.º 1
0
        public static Tokenresponse DoLoginAndAuthenticate(Config appConfig)
        {
            Tokenresponse authToken = null;

            //If AccessToken appears in appConfig, skip this steps and pass AccessToken the service directly.
            if (!string.IsNullOrEmpty(appConfig.AccessToken))
            {
                return(authToken);
            }

            if (DoLoginAndGetToken(out authToken, appConfig))
            {
                Console.WriteLine("Login Success!");
                if (appConfig.Verbose)
                {
                    DumpToken(authToken);
                }
            }
            else
            {
                Console.WriteLine("Login Terminated. Exit application.");
            }

            return(authToken);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Use this function to Refresh the Access Token
        /// </summary>
        /// <param name="username"> EDP username</param>
        /// <param name="refreshToken">The refresh token</param>
        /// <param name="client">AuthorizeClient object to call TokenAsync</param>
        /// <param name="cts">CancellationToken</param>
        /// <returns></returns>
        public static Tokenresponse RefreshToken(string username, string refreshToken, AuthorizeClient client,
                                                 CancellationToken cts)
        {
            Tokenresponse tokenResponse = null;

            tokenResponse = client.TokenAsync("refresh_token", username, "", "", "", refreshToken,
                                              username, "",
                                              "", "", "", cts).GetAwaiter().GetResult().Result;
            return(tokenResponse);
        }
        /// <summary>Used to print Token values. It will check if the Tokenreponse object is null before printing the properties</summary>
        /// <param name="token">The Tokenresponse object.</param>
        public static void DumpToken(Tokenresponse token)
        {
            if (token == null)
            {
                Console.WriteLine("Token is null");
                return;
            }

            Console.WriteLine($"AccessToken={token.Access_token}\n" +
                              $"Expired={token.Expires_in}\n" +
                              $"RefreshToken={token.Refresh_token}\n" +
                              $"Scope={token.Scope}\n" +
                              $"TokenType={token.Token_type}");
        }
Exemplo n.º 4
0
        private static void DumpToken(Tokenresponse token)
        {
            if (token == null)
            {
                Console.WriteLine("It's null token object");
                return;
            }

            Console.WriteLine("*************Token Details**************");
            Console.WriteLine($"AccessToken={token.Access_token}\n" +
                              $"Expired={token.Expires_in}\n" +
                              $"RefreshToken={token.Refresh_token}\n" +
                              $"Scope={token.Scope}\n" +
                              $"TokenType={token.Token_type}");
            Console.WriteLine("****************************************");
        }
        /// <summary>Used to refresh an access token</summary>
        /// <param name="username">The resource owner username (typically ClientID/RDP Username).</param>
        /// <param name="refreshToken">The refreshToken used to get a new Access Token from the RDP Server.</param>
        /// <param name="client">The AuthorizeClient object. Internal codes will call TokenAsync from the AuthorizeClient class to request a new token</param>
        /// <returns><see cref="Tokenresponse"/></returns>
        /// <exception cref="EDPAuthorizeException">A server side error occurred. Internal code will catch the exception and print to console output</exception>
        /// <exception cref="Exception">A general error occurred.Internal code will catch the exception and print to console output</exception>

        public static Tokenresponse RefreshToken(string username, string refreshToken, AuthorizeClient client)
        {
            Tokenresponse tokenResponse = null;

            try
            {
                tokenResponse = client.TokenAsync("refresh_token", username, "", "", "", refreshToken,
                                                  username, "",
                                                  "", "", "").GetAwaiter().GetResult().Result;
            }
            catch (EDPAuthorizeException <AuthError> edpAuthorizeException)
            {
                Console.WriteLine(
                    $"HttpStatusCode:{edpAuthorizeException.StatusCode} {edpAuthorizeException.Result.Error1} {edpAuthorizeException.Result.Error_description} {edpAuthorizeException.Result.Error_uri}");
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }

            return(tokenResponse);
        }
Exemplo n.º 6
0
        /// <summary> There is a loop inside the function to ask user to enter EDP username and password until it get a valid token.
        /// User can press Ctrl+c to exit from the loop and exit the application</summary>
        /// <return>True if login success and False if user cancelled the login</return>
        /// <param name="appConfig"> Required appConfig to read config parameters. </param>
        /// <param name="authToken"> Application has to pass Tokenresponse object to the function and
        /// the function will return Tokenresponse to application. It could be null if user cancelled the login </param>

        public static bool DoLoginAndGetToken(out Tokenresponse authToken, Config appConfig)
        {
            authToken = null;
            var bCancelledLogin = false;
            var cts             = new CancellationTokenSource();

            Console.TreatControlCAsInput = false;
            Console.CancelKeyPress      += (s, ev) =>
            {
                bCancelledLogin = true;
                ev.Cancel       = true;
                cts.Cancel();
            };
            do
            {
                Console.WriteLine("\nSignin to RDP(Refinitiv Data Platform) Press Ctrl+C to cancel");
                Console.WriteLine("=============================");


                if (bCancelledLogin)
                {
                    break;
                }

                if (string.IsNullOrEmpty(appConfig.Username))
                {
                    Console.Write("Machine ID or Username(Email):");
                    appConfig.Username = Console.ReadLine();
                }
                else
                {
                    Console.WriteLine($"Machine ID or Username(Email):{appConfig.Username}");
                }
                //if (!RegexUtilities.IsValidEmail(appConfig.Username))
                //{
                //assume that client use machine ID and assign machine id to client id.
                //    appConfig.ClientId = appConfig.Username;
                //}
                //else
                //{
                if (string.IsNullOrEmpty(appConfig.ClientId))
                {
                    Console.Write("Enter Client ID/AppKey:");
                    appConfig.ClientId = Console.ReadLine();
                }
                else
                {
                    Console.WriteLine($"Client ID:{appConfig.ClientId}");
                }
                //}

                if (!bCancelledLogin && string.IsNullOrEmpty(appConfig.RefreshToken) && string.IsNullOrEmpty(appConfig.Password))
                {
                    Console.Write("Enter Password:"******"=============================");

                if (bCancelledLogin)
                {
                    break;
                }

                Console.WriteLine("Logging in to the EDP server, please wait");

                using (var client = new HttpClient(GenerateHttpClientHandler(appConfig)))
                {
                    var authClient = new AuthorizeClient(client);

                    //If user specify authorize token url vi app config, it overrides default authorize url.
                    if (!string.IsNullOrEmpty(appConfig.AuthBaseURL))
                    {
                        authClient.BaseUrl = appConfig.AuthBaseURL;
                    }

                    try
                    {
                        authToken = string.IsNullOrEmpty(appConfig.RefreshToken)
                                        ? GetNewToken(appConfig.Username, appConfig.Password, appConfig.ClientId, authClient, cts.Token)
                                        : RefreshToken(
                            appConfig.Username,
                            appConfig.RefreshToken,
                            authClient,
                            cts.Token);
                    }
                    catch (EDPAuthorizeException <AuthError> exception)
                    {
                        Console.WriteLine(
                            $"Login Failed! Status Code:{exception.StatusCode} "
                            + $"Error:{exception.Result.Error1} {exception.Result.Error_description} {exception.Result.Error_uri}");
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine($"\nGet {exception.GetType().Name} Error {exception.Message}");
                    }
                    finally
                    {
                        //reset everything to empty and ask user to enter credential again.
                        appConfig.Username     = string.Empty;
                        appConfig.Password     = string.Empty;
                        appConfig.RefreshToken = string.Empty;
                        appConfig.ClientId     = string.Empty;
                        //Console.WriteLine("\nRe-enter EDP username and password or press Ctrl+C to exit");
                    }
                }
            } while (!bCancelledLogin && (authToken == null));

            return(!bCancelledLogin && (authToken != null));
        }