/// <summary>
        /// Creates <see cref="ImapClient"/> instance.
        /// </summary>
        /// <param name="credentials"><see cref="MailCredentials"/> instance.</param>
        /// <param name="errorMessages"><see cref="ImapErrorMessages"/> instance.</param>
        /// <param name="userConnection"><see cref="UserConnection"/> instance.</param>
        /// <param name="login">Flag indicates if need to login to imap server.</param>
        public ImapClient(MailCredentials credentials, ImapErrorMessages errorMessages, UserConnection userConnection, bool login = true)
        {
            _userConnection     = userConnection;
            _client             = CreateImapClient(credentials);
            _remoteChangesCount = 0;
            LocalChangesCount   = 0;
            string errorMessage = string.Empty;

            try {
                _currentMailboxName = credentials.SenderEmailAddress;
                if (login)
                {
                    string oauthClassName = GetOAuthClientClassNameBySender(_currentMailboxName);
                    if (oauthClassName.IsNotNullOrEmpty())
                    {
                        errorMessage = LocInvalidOAuthCredentials.ToString();
#if !NETSTANDARD2_0 // TODO #CRM-42481
                        OAuthClient oauthClient = (OAuthClient)Activator.CreateInstance(Type.GetType("Terrasoft.Configuration." + oauthClassName), credentials.SenderEmailAddress, userConnection);
                        string      token       = oauthClient.GetAccessToken();
#else
                        string token = string.Empty;
#endif
                        string xoAuthKey = OAuth2.GetXOAuthKeyStatic(credentials.SenderEmailAddress, token);
                        _client.Login(credentials.UserName, xoAuthKey, AuthenticationMethods.SaslOAuth2, MailBee.AuthenticationOptions.None, null);
                    }
                    else
                    {
                        errorMessage = LocLoginOrPwdWrong.ToString();
                        _client.Login(credentials.UserName, credentials.UserPassword);
                    }
                }
            } catch (Exception ex) {
                throw new ImapException(errorMessage, ex);
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ApiClient" /> class.
 /// </summary>
 /// <param name="apiKey">The api key.</param>
 /// <param name="apiSid">The api sid.</param>
 /// <param name="basePath">The base path.</param>
 public ApiClient(String apiKey, String apiSid, String basePath = "http://api.aspose.cloud/v1.1")
 {
     BasePath                 = basePath;
     authenticator            = new OAuth2(apiSid, apiKey);
     RestClient               = new RestClient(BasePath);
     RestClient.Authenticator = authenticator;
 }
        public async Task <IOAuth2Account> AuthenticateAsync(IOAuth2Options options)
        {
            oauth = new OAuth2(options);

            var url = await oauth.GetInitialUrlAsync();

            var svc = new SFSafariViewController(NSUrl.FromString(url.AbsoluteUri))
            {
                Delegate = new NativeSFSafariViewControllerDelegate
                {
                    DidFinishHandler = (obj) =>
                    {
                        tcsAuth.TrySetResult(default(IOAuth2Account));
                    }
                }
            };

            tcsAuth = new TaskCompletionSource <IOAuth2Account>();


            await Plugin.SocialAuth.iOS.SocialAuth.PresentingViewController.PresentViewControllerAsync(svc, true);


            return(await tcsAuth.Task);
        }
Exemplo n.º 4
0
        internal void GenerateOAuth2Token(string oAuthEndPoint, string oAuthParameters)
        {
            string oAuthParams     = oAuthParameters.Replace(" And ", ",");
            var    oauthParameters = oAuthParams.Split(',');

            var allParameters = new Dictionary <string, string>();

            foreach (var key in oauthParameters)
            {
                try
                {
                    string value = TestContext.Properties["Parameter:" + key].ToString() ?? "";
                    allParameters.Add(key, value);
                }
                catch { }
            }

            string authorizationServer = TestContext.Properties["Parameter:authserver"].ToString();
            string requestString       = EndPoint.GetEndpoint(authorizationServer);
            string parameters          = Helper.DictionaryToQueryParametersList(allParameters);

            Console.WriteLine($"Printing endpoint and parameters for oauth2 request {requestString + parameters}");
            var    oauth2Token = new OAuth2();
            string oAuthToken  = oauth2Token.GetOAuthToken(requestString + parameters);

            RequestParameters.SetHeaders(_authHeader, "Bearer " + oAuthToken);
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var color = new Config().LoginBackgroundColor;

            if (color != null)
            {
                grid.Background = new SolidColorBrush(color.Value);
            }
            Account account = AccountManager.GetAccount();

            if (account != null)
            {
                try
                {
                    account = await OAuth2.RefreshAuthToken(account);

                    _contacts = await SendRequest("SELECT Name FROM Contact");

                    contactList.DataContext = Contacts;
                }
                catch (OAuthException ex)
                {
                    SDKManager.GlobalClientManager.Logout();
                }
            }
            else
            {
                base.OnNavigatedTo(e);
            }
        }
Exemplo n.º 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            OAuth2    oauthContainer = PhishyHelper.getFidorOauth2Container(this.Context.IsDebuggingEnabled);
            APIAccess fidorApi       = new APIAccess();

            fidorApi.GetAccessToken(oauthContainer, null);
        }
        /// <summary>
        ///     When navigated to, we try to get a RestClient
        ///     If we are not already authenticated, this will kick off the login flow
        /// </summary>
        /// <param name="e"></param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            Account account = AccountManager.GetAccount();

            if (account != null)
            {
                if (!oneView.CanGoBack)
                {
                    try
                    {
                        account = await OAuth2.RefreshAuthToken(account);

                        string startPage = OAuth2.ComputeFrontDoorUrl(account.InstanceUrl,
                                                                      LoginOptions.DefaultDisplayType,
                                                                      account.AccessToken, GetPage(account));

                        oneView.Navigate(new Uri(startPage));
                    }
                    catch (OAuthException ex)
                    {
                        SDKManager.GlobalClientManager.Logout();
                    }
                }
            }
            else
            {
                base.OnNavigatedTo(e);
            }
        }
Exemplo n.º 8
0
        public async Task <IActionResult> testOAuthAsync()
        {
            OAuth2             oauth    = new OAuth2("*****@*****.**");
            List <MimeMessage> messages = oauth.ReceiveEmail(1);

            return(View("Done"));
        }
Exemplo n.º 9
0
        public async Task BuildsCodeFormCorrect()
        {
            var form   = OAuth2.BuildAuthTokenForm("cid", "cis", "12345");
            var output = await form.ReadAsStringAsync();

            Assert.Equal("client_id=cid&client_secret=cis&grant_type=authorization_code&code=12345", output);
        }
Exemplo n.º 10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //Instantiate an OAuth2 object
            OAuth2 oAuth2 = new OAuth2();

            //Configure the parameters and callback URL
            oAuth2.client_id     = "f01805e4766ebdc5";
            oAuth2.client_secret = "be744c6869ffac80f421742f9aff0732";
            oAuth2.redirect_uri  = "http://localhost:3000/callback.aspx";

            //request if OAuth2 server has granted a code
            string code = Request.QueryString["code"];

            //Instantiate a status object
            APIAccess.Result status = new APIAccess.Result();
            status.result = -1;
            status.value  = "";

            //Instantiate a APIAccess object
            APIAccess fidorapi = new APIAccess();

            //Status returned from GetAccessToken API
            status = fidorapi.GetAccessToken(oAuth2, code);

            if (status.result == 0)
            {
                //save the access token
                Session["AccessToken"] = status.value;
                //go to a main page
                Response.Redirect("Index.aspx");
            }
        }
Exemplo n.º 11
0
        public async Task BuildsRefreshFormCorrect()
        {
            var form   = OAuth2.BuildRefreshTokenForm("cid", "cis", "12345");
            var output = await form.ReadAsStringAsync();

            Assert.Equal("client_id=cid&client_secret=cis&grant_type=refresh_token&refresh_token=12345", output);
        }
Exemplo n.º 12
0
        // Notes:
        //  - This class handles interaction with online sources. It basically
        //    wraps HttpClient and provides functions for downloaded data files.

        public Web(CancellationToken shutdown)
        {
            Client = new HttpClient();
            Client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
            OAuth    = new OAuth2("51b7781a-c48c-42de-b527-7267014cb64c", "");
            Shutdown = shutdown;
        }
Exemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ApiClient" /> class.
 /// </summary>
 /// <param name="apiKey">The api key.</param>
 /// <param name="apiSid">The api sid.</param>
 /// <param name="basePath">The base path.</param>
 public ApiClient(String appKey, String appSid, String basePath = "https://localhost/v1.1")
 {
     BasePath                  = basePath;
     authenticator             = new OAuth2(appSid, appKey);
     _restClient               = new RestClient(BasePath);
     _restClient.Authenticator = authenticator;
 }
        public void SetUp()
        {
            LoginOptions loginOptions = new LoginOptions(TestCredentials.LOGIN_URL, TestCredentials.CLIENT_ID, null, null);

            _accessToken = OAuth2.RefreshAuthToken(loginOptions, TestCredentials.REFRESH_TOKEN).Result.AccessToken;
            _restClient  = new RestClient(TestCredentials.INSTANCE_SERVER, _accessToken, null);
        }
Exemplo n.º 15
0
        private OAuth2 GetOauth2Model()
        {
            var oauth2Token = new OAuth2 {
                ClientId = _clientId, ClientSecret = _secretKey
            };

            if (_usePassword)
            {
                oauth2Token.GrantType = GrantType.password;
                oauth2Token.UserName  = _userName;
                oauth2Token.Password  = _password;
                _usePassword          = false;
            }
            else if (_useAuthorizationCode)
            {
                oauth2Token.GrantType = GrantType.authorization_code;
                oauth2Token.Code      = _authorizationCode;
                _useAuthorizationCode = false;
            }
            else
            {
                oauth2Token.GrantType    = GrantType.refresh_token;
                oauth2Token.RefreshToken = _currentOAuthToken.RefreshToken;
            }

            return(oauth2Token);
        }
Exemplo n.º 16
0
        // Call MusicBrainz API to get artist songs
        private List <SongList> GetArtistSongs(string artistID)
        {
            if (string.IsNullOrEmpty(artistID))
            {
                return(new List <SongList>());
            }

            // This is taken from Github documentation
            // https://github.com/Zastai/MetaBrainz.MusicBrainz/blob/master/UserGuide.md

            var oa = new OAuth2();

            oa.ClientId = "mJAE1ZhAnqLnC3Pg6Hnt9Q85V0PA-Qgo";
            // If using a local MusicBrainz server instance, make sure to set up the correct address and port.
            var url = oa.CreateAuthorizationRequest(OAuth2.OutOfBandUri, AuthorizationScope.Rating | AuthorizationScope.Tag);
            var at  = oa.GetBearerToken(LoginHelper.GetAccessToken(), "ahb54cxChyLFXebAX4BFMezbm6IgXXac", OAuth2.OutOfBandUri);
            var q   = new MetaBrainz.MusicBrainz.Query("Red Stapler", "19.99", "mailto:[email protected]");

            q.BearerToken = at.AccessToken;
            var artist = q.BrowseArtistWorks(new Guid(artistID));

            q.Close();

            return(GetArtistSongsFromResult(artist.Results));
        }
Exemplo n.º 17
0
        public void Test_OAuth2_ClientCredentials()
        {
            const string expectedUri = @"https://api.soundcloud.com/oauth2/token?";

            var accessRequest = new Credentials();

            accessRequest.client_id     = "my client id";
            accessRequest.client_secret = "my client secret";

            var response = new ApiResponse <Credentials>(HttpStatusCode.OK, "OK");

            response.Data = accessRequest;

            var gatewayMock = new Mock <ISoundCloudApiGateway>(MockBehavior.Strict);

            gatewayMock.Setup(x => x.InvokeCreateRequest <Credentials>(It.Is <Uri>(y => y.ToString() == expectedUri), It.IsAny <IDictionary <string, object> >()))
            .Returns(response)
            .Callback((Uri u, IDictionary <string, object> p) =>
            {
                Assert.That(p["client_id"], Is.EqualTo("my client id"));
                Assert.That(p["client_secret"], Is.EqualTo("my client secret"));
                Assert.That(p["grant_type"], Is.EqualTo("client_credentials"));
            });

            var oauth2Endpoint = new OAuth2(gatewayMock.Object);

            var result = oauth2Endpoint.ClientCredentials(accessRequest);

            Assert.That(result, Is.InstanceOf <SuccessWebResult <Credentials> >());
            Assert.That(result.IsSuccess, Is.True);
            Assert.That(result.ErrorMessage, Is.EqualTo(string.Empty));
        }
Exemplo n.º 18
0
        public Form1()
        {
            InitializeComponent();

            this.BringToFront();
            this.Focus();
            this.KeyPreview = true;

            Index           = 0; Pages = new List <Tuple <string, Status> >();
            button1.Enabled = button2.Enabled = false;

            if (BearerToken.Equals("none"))
            {
                try
                {
                    BearerToken = OAuth2.GetToken(ConsumerKey, ConsumerSecret).BearerToken;
                    Properties.Settings.Default.Save();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                    Environment.Exit(1);
                }
            }
            Token = OAuth2Token.Create(ConsumerKey, ConsumerSecret, BearerToken);
            toolStripTextBox1.Focus();
        }
        /// <summary>
        ///     Returns a RestClient if user is already authenticated or null
        /// </summary>
        /// <returns></returns>
        public IRestClient PeekRestClient()
        {
            Account account = AccountManager.GetAccount();

            if (account != null)
            {
                return(new RestClient(account.InstanceUrl, account.AccessToken,
                                      async() =>
                {
                    account = AccountManager.GetAccount();

                    try
                    {
                        account = await OAuth2.RefreshAuthTokenAsync(account);
                    }
                    catch (DeviceOfflineException)
                    {
                        LoggingService.Log("Could not refresh the token because device is offline", LoggingLevel.Warning);
                        return null;
                    }
                    catch (OAuthException ex)
                    {
                        LoggingService.Log("Failed to refresh the token, logging the user out", LoggingLevel.Warning);
                        LoggingService.Log(ex, LoggingLevel.Error);

                        // we failed to refresh the token, we have to log the user out
                        await Logout();
                    }

                    return account.AccessToken;
                }
                                      ));
            }
            return(null);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Chiamare per prolungare la validità del token di accesso.
        /// </summary>
        /// <returns>Restituisce l'eventuale token di accesso aggiornato.
        /// In caso di errore, viene restituita stringa vuota.</returns>
        public async Task <string> Refresh()
        {
            if (!IsLoggedIn())
            {
                Debug.WriteLine("Token refresh failed!\nUser is not logged in.");
                return(string.Empty);
            }

            try
            {
                await OAuth2.RefreshToken(Account,
                                          Uri.EscapeUriString(IDApplication),
                                          new Uri(URLCallaback),
                                          AppSecret,
                                          new Uri(URLToken));

                if (Account.AccessToken.Length <= 0)
                {
                    throw new Exception("Token refresh failed! The new token is empty");
                }

                // Aggiorna anche i dati accesso precedente serializzati in file
                RefreshAccessData();

                Debug.WriteLine("Token refreshed!");
                return(Account.AccessToken);
            }
            catch (Exception e)
            {
                LastError = e.Message;
                Debug.WriteLine(AppResources.errCloudRefreshToken2 + " " + e.Message);
                return(string.Empty);
            }
        }
        private static OAuth2 MatchFlow(Flow flowspec, string flow)
        {
            var oauth2 = new OAuth2();

            switch (flow.ToLowerInvariant())
            {
            case "implicit":
                oauth2.Implicit = flowspec;
                break;

            case "authorizationcode":
                oauth2.AuthorizationCode = flowspec;
                break;

            case "clientcredentials":
                oauth2.ClientCredentials = flowspec;
                break;

            case "password":
                oauth2.Password = flowspec;
                break;
            }

            return(oauth2);
        }
        public void StartLoginFlow(LoginOptions loginOptions)
        {
            Uri loginUri    = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions));
            Uri callbackUri = new Uri(loginOptions.CallbackUrl);

            OAuth2.ClearCookies(loginOptions);
            WebAuthenticationBroker.AuthenticateAndContinue(loginUri, callbackUri, null, WebAuthenticationOptions.None);
        }
Exemplo n.º 23
0
        public async Task <IActionResult> OnGet(string code, string state)
        {
            if (code == null &&
                state == null)
            {
                return(Page());
            }
            else if (code.Equals("logout"))
            {
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                return(RedirectToPage("/"));
            }
            if (!state.Equals(Request.Host.GetHashCode().ToString(), StringComparison.CurrentCulture))
            {
                NotificationMessage = "Something went wrong while logging in";
                return(Page());
            }

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"https://discord.com/api/oauth2/token?client_id={SkyBotConfig.DiscordClientId}&client_secret={SkyBotConfig.DiscordClientSecret}&grant_type=authorization_code&code={code}&redirect_uri=http%3A%2F%2Fwindows.dra-gon.wtf%3A40005%2FLogin&scope=identify");

            //HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"https://discord.com/api/oauth2/token?client_id={SkyBotConfig.DiscordClientId}&client_secret={SkyBotConfig.DiscordClientSecret}&grant_type=authorization_code&code={code}&redirect_uri=https%3A%2F%2Flocalhost%3A44327%2FLogin&scope=identify");
            _ = request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
            request.Content = new FormUrlEncodedContent(new Dictionary <string, string>()
            {
                { "client_id", SkyBotConfig.DiscordClientId },
                { "client_secret", SkyBotConfig.DiscordClientSecret },
                { "grant_type", "authorization_code" },
                { "code", code },
                { "redirect_uri", "http://windows.dra-gon.wtf:40005/Login" },
                //{"redirect_uri", "https://*****:*****@me");
            request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {oauth.AccessToken}");

            response = await client.SendAsync(request);

            json = await response.Content.ReadAsStringAsync();

            DSharpPlus.Entities.DiscordUser user = Newtonsoft.Json.JsonConvert.DeserializeObject <DSharpPlus.Entities.DiscordUser>(json);

            if (user == null)
            {
                NotificationMessage = "Unable to get serialize user, please report this bug";
                return(Page());
            }

            return(await LoginUser((long)user.Id, user.Username));
        }
Exemplo n.º 24
0
        /// <summary>
        ///     Show remote page in cordova view
        /// </summary>
        protected void LoadRemoteStartPage()
        {
            var uri =
                new Uri(
                    OAuth2.ComputeFrontDoorUrl(_client.InstanceUrl, LoginOptions.DefaultDisplayType, _client.AccessToken,
                                               _bootConfig.StartPage), UriKind.Absolute);

            LoadUri(uri);
        }
Exemplo n.º 25
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string path = HttpContext.Current.Request.Url.ToString();

            if (Common.IsFromWechatBrowser() && !path.Contains("open.weixin.qq.com") && (HttpContext.Current.Request.QueryString["code"] == null || string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["code"].ToString())))
            {
                filterContext.Result = new RedirectResult(OAuth2.GetCode(ApiModel.AppID, path, Wechat.API.Enums.OAuthScopeEnum.snsapi_userinfo, "STATE"));
            }
        }
Exemplo n.º 26
0
        private IActionResult Auth(string scope, string state)
        {
            var appId = _settings.AppId;

            //相对网址变为绝对网址
            var callbackUrl = Url.Page("Auth", "AuthCallback", null, Request.Scheme);

            var redirectUrl = OAuth2.GetAuthorizeUrl(appId, callbackUrl, scope, state);

            return(Redirect(redirectUrl));
        }
Exemplo n.º 27
0
        /// <summary>
        /// When navigated to, we try to get a RestClient
        /// If we are not already authenticated, this will kick off the login flow
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            RestClient client = SalesforceApplication.GlobalClientManager.GetRestClient();

            if (client != null)
            {
                Account account   = AccountManager.GetAccount();
                String  startPage = OAuth2.ComputeFrontDoorUrl(account.InstanceUrl, account.AccessToken, account.LoginUrl + "/one/one.app");
                oneView.Navigate(new Uri(startPage));
            }
        }
Exemplo n.º 28
0
        public void EnsureHeaderAndTokenUsedCorrectly()
        {
            IAuthHeaderDataProvider provider = new FakeAuthHeaderProvider();
            OAuth2 oauth = new OAuth2(provider);

            var headersProvider = oauth.CreateHeaders();

            Assert.IsNotNull(headersProvider, "Expected headers");
            Assert.AreEqual(1, headersProvider.Count, "Expected one header");
            Assert.AreEqual("Authorization", headersProvider.Keys.First(), "Expected Authorization header");
        }
Exemplo n.º 29
0
        public async Task <string> Authenticate()
        {
            var oa = new OAuth2
            {
                ClientId = ClientId,
            };
            var url = oa.CreateAuthorizationRequest(OAuth2.OutOfBandUri, AuthorizationScope.Rating | AuthorizationScope.Tag);
            var at  = await oa.GetBearerTokenAsync("code", ClientSecret, OAuth2.OutOfBandUri);

            return(at.AccessToken);
        }
Exemplo n.º 30
0
        private ActionResult Auth(string scope, string state)
        {
            var appId = ConfigurationManager.AppSettings["weixin.appId"];

            //相对网址变为绝对网址
            var callbackUrl = new Uri(Request.Url, Url.Action("AuthCallback")).ToString();

            var redirectUrl = OAuth2.GetAuthorizeUrl(appId, callbackUrl, scope, state);

            return(Redirect(redirectUrl));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuth2AuthorizationRequestHeaderAuthenticator"/> class.
 /// </summary>
 /// <param name="client">The OAuth2 client</param>
 /// <param name="tokenType">The token type.</param>
 public OAuth2AuthorizationRequestHeaderAuthenticator(OAuth2.OAuth2Client client, string tokenType)
     : base(client)
 {
     _tokenType = tokenType;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuth2AuthorizationRequestHeaderAuthenticator"/> class.
 /// </summary>
 /// <param name="client">The OAuth2 client</param>
 public OAuth2AuthorizationRequestHeaderAuthenticator(OAuth2.OAuth2Client client)
     : this(client, string.IsNullOrEmpty(client.TokenType) ? "OAuth" : client.TokenType)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuth2Authenticator"/> class.
 /// </summary>
 /// <param name="client">The OAuth2 client</param>
 protected OAuth2Authenticator(OAuth2.OAuth2Client client)
 {
     Client = client;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuth2Authenticator"/> class.
 /// </summary>
 /// <param name="client">The OAuth2 client</param>
 protected OAuth2Authenticator(OAuth2.OAuth2Client client)
     : this(client, TimeSpan.FromSeconds(60))
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuth2UriQueryParameterAuthenticator"/> class.
 /// </summary>
 /// <param name="client">The OAuth2 client</param>
 public OAuth2UriQueryParameterAuthenticator(OAuth2.OAuth2Client client)
     : base(client)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuth2Authenticator"/> class.
 /// </summary>
 /// <param name="client">The OAuth2 client</param>
 /// <param name="challengeTimespan">The time span that has to be exceeded before a new challenge can be handled</param>
 protected OAuth2Authenticator(OAuth2.OAuth2Client client, TimeSpan challengeTimespan)
 {
     Client = client;
     ChallengeTimespan = challengeTimespan;
 }