Esempio n. 1
0
        public async Task <TwitterAccessTokenResponse> GetAccessTokenAsync(string loginToken, string oauthToken, string oauthVerifier)
        {
            var oauth = new Oauth(_configuration.AppId, _configuration.AppSecret, AccessTokenUri)
            {
                AccessSecret = loginToken
            };

            oauth.AddOauthParameter("token", oauthToken);
            oauth.AddParameter("oauth_verifier", oauthVerifier);

            try
            {
                var oauthResult = await oauth.DoRequest();

                return(new TwitterAccessTokenResponse
                {
                    ScreenName = oauthResult["screen_name"],
                    UserId = oauthResult["user_id"]
                });
            }
            catch (Exception ex)
            {
                throw new TwitterClientException(ex);
            }
        }
Esempio n. 2
0
 public void MergeFrom(AuthenticationRule other)
 {
     if (other == null)
     {
         return;
     }
     if (other.Selector.Length != 0)
     {
         Selector = other.Selector;
     }
     if (other.oauth_ != null)
     {
         if (oauth_ == null)
         {
             oauth_ = new global::Google.Api.OAuthRequirements();
         }
         Oauth.MergeFrom(other.Oauth);
     }
     if (other.AllowWithoutCredential != false)
     {
         AllowWithoutCredential = other.AllowWithoutCredential;
     }
     requirements_.Add(other.requirements_);
     _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
 }
Esempio n. 3
0
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

            if (!result.IsSuccessful)
            {
                return(RedirectToAction("ExternalLoginFailure"));
            }

            Session[Oauth.FieldNames.AccessToken] = result.ExtraData.ReadField(Oauth.FieldNames.AccessToken);

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                Oauth.UpdateUserAsync(result);
                return(RedirectToLocal(returnUrl));
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl           = returnUrl;
                return(View("ExternalLoginConfirmation", new RegisterExternalLoginModel {
                    UserName = result.UserName, ExternalLoginData = loginData
                }));
            }
        }
        public void Post_UnvalidAuthCode_TictailException()
        {
            var oauth = new Oauth
            {
                AuthCode     = "authcode_BAD",
                ClientId     = "clientid_ABCDEFGHIJKLM9876543",
                ClientSecret = "clientsecret_123456789abcdefghij"
            };

            const string tictailJsonReponse = "{" +
                                              "\"status\": 400, " +
                                              "\"message\": \"Invalid authorization code given\"," +
                                              "\"params\": {}, " +
                                              "\"support_email\": \"[email protected]\"" +
                                              "}";

            var testClient = new TictailClientTest
            {
                Content        = tictailJsonReponse,
                ResponseStatus = ResponseStatus.Completed,
                StatusCode     = HttpStatusCode.BadRequest
            };

            var sut = new OauthRepository(testClient);

            var tictailException = Assert.Throws <TictailException>(() => sut.Post(oauth));

            Assert.Equal(400, tictailException.Status);
            Assert.Equal("Invalid authorization code given", tictailException.Message);
            Assert.Equal("*****@*****.**", tictailException.SupportEmail);
        }
Esempio n. 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsCallback)
            {
                Oauthkey2 oauthKey = new Oauthkey2(
                    StringParserHelper.GetConfig("AppKey"),
                    StringParserHelper.GetConfig("AppSercet"));

                oauthKey.ParseToken(this.Request.Url.ToString());
                oauthKey.callbackUrl = StringParserHelper.GetConfig("CallbackUrl");

                var oauth2      = new Oauth(oauthKey);
                var accessToken = oauth2.GetAccessToken();

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    this.Response.Write("获取Access_Token失败");
                }
                this.Session["accessToken"] = accessToken;
                txtMsg.Text = "授权成功,accessToken:" + accessToken;
                var user = new user(oauthKey, "UTF-8").info();

                txtUserInfo.Text = "账户信息:\r\n" + user;
            }
        }
        /// <summary>
        /// All is OK : used by Post_ValidAuthCode_AccessToken
        /// </summary>
        /// <param name="oauth">The oauth data going in</param>
        /// <returns>A token</returns>
        public Token Post(Oauth oauth)
        {
            const string tictailJsonReponse = "{" +
                                              "\"access_token\": \"accesstoken_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"," +
                                              "\"token_type\": \"Bearer\"," +
                                              "\"expires_in\": 3155760000," +
                                              "\"store\": {" +
                                              "\"id\": \"ab1\"," +
                                              "\"name\": \"Some example store\"," +
                                              "\"language\": \"en\"," +
                                              "\"url\": \"http://example.tictail.com\"," +
                                              "\"storekeeper_email\": \"[email protected]\"," +
                                              "\"created_at\": \"1999-02-12T20:10:20\"," +
                                              "\"modified_at\": null" +
                                              "}" +
                                              "}";

            var testClient = new TictailClientTest
            {
                Content        = tictailJsonReponse,
                ResponseStatus = ResponseStatus.Completed,
                StatusCode     = HttpStatusCode.OK
            };

            var sut = new OauthRepository(testClient);

            return(sut.Post(oauth));
        }
Esempio n. 7
0
        public void TestGetAccessToken()
        {
            Config.ClientSecret = "d4c253e584f54bf378b55618d7f05b998FD13D0D6C";
            string code = "eeede5a5c9a0f73f376a5735b14cae5c"; //测试时先手动获取CODE,写到这里,然后进行下面的各项测试
            var    ret  = Oauth.GetTokenWithUserinfo(code);

            Assert.IsNotNull(ret);
        }
Esempio n. 8
0
        public void TestGetToken()
        {
            Config.ClientSecret = "";  //测试时变更为实际值
            //应用授权测试
            var ret = Oauth.GetToken();

            Assert.IsNotNull(ret);
            Assert.IsTrue(ret.expires_in > 0);
        }
    public static Client CreateClient(this TwitterKeys keys)
    {
        var oauth = new Oauth(
            keys.ConsumerKey,
            keys.ConsumerSecret,
            keys.AccessToken,
            keys.AccessTokenSecret);

        return(new Client(oauth));
    }
Esempio n. 10
0
        public ActionResult GetFbData(string id = "me")
        {
            var fb = Oauth.GetUserFacebookClient();

            var test = fb.Get(id);

            return(Content(JsonConvert.SerializeObject(test), "application/json"));

            return(Json(test, JsonRequestBehavior.AllowGet));
        }
Esempio n. 11
0
        /// <summary>
        /// Post token request back to Tictail
        /// </summary>
        /// <param name="oauth">Oauth object</param>
        /// <returns>A token</returns>
        public Token Post(Oauth oauth)
        {
            var request = new RestRequest("oauth/token", Method.POST);

            request.AddParameter("application/x-www-form-urlencoded", oauth.GenerateBody(), ParameterType.RequestBody);

            string content = _client.ExecuteRequest(request, HttpStatusCode.OK).Content;

            return(DeserializeGet(content));
        }
Esempio n. 12
0
        public bool SendInvite(string userId, int listId)
        {
            var     fb     = Oauth.GetAppFacebookClient();
            dynamic result = fb.Post(userId + "/apprequests",
                                     new { appId = Oauth.FbAppId, message = "check out this app" });
            var reqId = result.request;
            var to    = result.to;

            return(true);
            //return result;
        }
Esempio n. 13
0
        public MessageFromBotToYnabConverter(IMessageSender messageSender, IBank[] banks, YnabDbContext dbContext, Oauth oauth)
        {
            this.messageSender = messageSender;
            this.banks         = banks;
            this.dbContext     = dbContext;

            this.oauth = oauth;
            users      = dbContext.Users.Include(item => item.BankAccountToYnabAccounts).
                         ThenInclude(item => item.YnabAccount).
                         Include(item => item.DefaultYnabAccount).
                         Include(item => item.Access).
                         ToList();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        }
Esempio n. 14
0
        public User(IMessageSender messageSender, IDbSaver dbSaver, Oauth oauth)
        {
            this.messageSender = messageSender;
            this.dbSaver       = dbSaver;
            this.oauth         = oauth;

            machine = new StateMachine <State, Trigger>(State.Unknown);
            SetupTriggers();
            SetupStateUnknown();
            SetupStateAuthorizing();
            SetupStateEnteringDefaultBudget();
            SetupStateEnteringDefaultAccount();
            SetupStateReady();
            SetupStateApplyingSettings();
        }
        private async Task <Oauth> getAccessToken()
        {
            if (oauth != null && oauth.isExpired() == false)
            {
                return(oauth);
            }

            var encodedData = System.Convert.ToBase64String(
                System.Text.Encoding.GetEncoding("ISO-8859-1")
                .GetBytes(clientId + ":" + clientSecret)
                );
            var base64 = "Basic " + encodedData;

            var url = "";

            if (mode.Equals(Constants.SANDBOX))
            {
                url = Constants.REST_SANDBOX_ENDPOINT;
            }
            else if (mode.Equals(Constants.LIVE))
            {
                url = Constants.REST_LIVE_ENDPOINT;
            }
            else
            {
                throw new ArgumentException($"Mode must be {Constants.SANDBOX} or {Constants.LIVE}");
            }

            url += Constants.OAUTH_TOKEN_URI;


            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add(Constants.HTTP_ACCEPT_HEADER, Constants.HTTP_APPLICATION_JSON);
            client.DefaultRequestHeaders.Add(Constants.HTTP_AUTHORIZATION_HEADER, base64);

            var keyValues = new List <KeyValuePair <string, string> >();

            keyValues.Add(new KeyValuePair <string, string>("scope", "read,write"));
            keyValues.Add(new KeyValuePair <string, string>("grant_type", "client_credentials"));

            var res = await client.PostAsync(url, new FormUrlEncodedContent(keyValues));

            var resContent = await res.Content.ReadAsStringAsync();

            oauth = JsonConvert.DeserializeObject <Oauth>(resContent);

            return(oauth);
        }
        public void Post_ValidAuthCode_AccessToken()
        {
            var oauth = new Oauth
            {
                AuthCode     = "authcode_abcdefghijklmnop123456",
                ClientId     = "clientid_ABCDEFGHIJKLM9876543",
                ClientSecret = "clientsecret_123456789abcdefghij"
            };

            var token = Post(oauth);


            Assert.Equal("accesstoken_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", token.AccessToken);
            Assert.Equal("Bearer", token.TokenType);
            Assert.Equal(3155760000, token.ExpiresIn);
            Assert.NotNull(token.Store);
        }
Esempio n. 17
0
    // Use this for initialization
    void Start()
    {
        gameSystem = (GameSystemScript)(GameObject.Find("GameSystem").GetComponent("GameSystemScript"));

        var oauth = new Oauth(
            SettingManager.Keys.ConsumerKey,
            SettingManager.Keys.ConsumerSecret,
            SettingManager.Keys.AccessToken,
            SettingManager.Keys.AccessTokenSecret);

        client = new Client(oauth);

        Dictionary <string, string> parameters = new Dictionary <string, string>();

        parameters["count"] = (SettingManager.GameParams.AllTweetCount).ToString();
        StartCoroutine(ShowTimeLine("statuses/home_timeline", parameters, this.Callback));
    }
Esempio n. 18
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Selector.Length != 0)
            {
                hash ^= Selector.GetHashCode();
            }
            if (oauth_ != null)
            {
                hash ^= Oauth.GetHashCode();
            }
            if (AllowWithoutCredential != false)
            {
                hash ^= AllowWithoutCredential.GetHashCode();
            }
            hash ^= requirements_.GetHashCode();
            return(hash);
        }
Esempio n. 19
0
    public void ClickTitleStart()
    {
        if (isRequesting)
        {
            return;
        }
        isRequesting = true;
        var oauth = new Oauth(
            SettingManager.Keys.ConsumerKey,
            SettingManager.Keys.ConsumerSecret,
            SettingManager.Keys.AccessToken,
            SettingManager.Keys.AccessTokenSecret);
        var client = new Client(oauth);

        Dictionary <string, string> parameters = new Dictionary <string, string>();

        parameters["include_email"] = "false";
        StartCoroutine(client.Get("account/verify_credentials", parameters, this.Callback));
    }
Esempio n. 20
0
        public async Task <TwitterRequestTokenResponse> GetRequestTokenAsync()
        {
            var oauth = new Oauth(_configuration.AppId, _configuration.AppSecret, RequestTokenUri);

            oauth.AddOauthParameter("callback", _configuration.Callback);

            try
            {
                var oauthResult = await oauth.DoRequest();

                return(new TwitterRequestTokenResponse
                {
                    OAuthToken = oauthResult["oauth_token"]
                });
            }
            catch (Exception ex)
            {
                throw new TwitterClientException(ex);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Attempt to get and set an OAuth token with client id, username, and password
        /// </summary>
        public void LoginAsUser(string clientId, string username, string password)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new ApiException(400, "Missing required paramater clientId");
            }
            if (string.IsNullOrEmpty(username))
            {
                throw new ApiException(400, "Missing required paramater username");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ApiException(400, "Missing required paramater password");
            }
            var token = Oauth.GetOauthToken("password",
                                            clientId,
                                            username: username,
                                            password: password);

            this.Configuration.AccessToken = token.AccessToken;
        }
Esempio n. 22
0
        //ͬ��http����
        public string SyncRequest(string url, string httpMethod, OauthKey key, List<Parameter> listParam, List<Parameter> listFile)
        {
            Oauth oauth = new Oauth();

            string queryString = null;
            string oauthUrl = oauth.GetOauthUrl(url, httpMethod, key.customKey, key.customSecret,
                key.tokenKey, key.tokenSecret, key.verify, key.callbackUrl, listParam, out queryString);

            SyncHttp http = new SyncHttp();
            if (httpMethod == "GET")
            {
                return http.HttpGet(oauthUrl, queryString);
            }
            else if ((listFile == null) || (listFile.Count == 0))
            {
                return http.HttpPost(oauthUrl, queryString);
            }
            else
            {
                return http.HttpPostWithFile(oauthUrl, queryString, listFile);
            }
        }
Esempio n. 23
0
        //�첽http����
        public bool AsyncRequest(string url, string httpMethod, OauthKey key, List<Parameter> listParam, List<Parameter> listFile,
            AsyncRequestCallback callback, out int callbkey)
        {
            Oauth oauth = new Oauth();

            string queryString = null;
            string oauthUrl = oauth.GetOauthUrl(url, httpMethod, key.customKey, key.customSecret,
                key.tokenKey, key.tokenSecret, key.verify, key.callbackUrl, listParam, out queryString);

            AsyncHttp http = new AsyncHttp();

            callbkey = GetKey();
            CallbackInfo callbackInfo = new CallbackInfo();
            callbackInfo.key = callbkey;
            callbackInfo.callback = callback;

            asyncRquestMap.Add(http, callbackInfo);

            bool bResult = false;

            if (httpMethod == "GET")
            {
                bResult = http.HttpGet(oauthUrl, queryString, new AsyncHttpCallback(HttpCallback));
            }
            else if ((listFile == null) || (listFile.Count == 0))
            {
                bResult = http.HttpPost(oauthUrl, queryString, new AsyncHttpCallback(HttpCallback));
            }
            else
            {
                bResult = http.HttpPostWithFile(oauthUrl, queryString, listFile, new AsyncHttpCallback(HttpCallback));
            }

            if (!bResult)
            {
                asyncRquestMap.Remove(http);
            }
            return bResult;
        }
Esempio n. 24
0
        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
        private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            if (_appSettings.Contains("authenticated"))
            {
                Oauth.Visibility       = Visibility.Collapsed;
                UserDetails.Visibility = Visibility.Visible;
            }
            else
            {
                Oauth.VerifiedCodeReceived += async(s, ec) =>
                {
                    OAuth2Sample auth = s as OAuth2Sample;
                    if (auth != null)
                    {
                        copyClient = await copyConfig.GetAccessTokenAsync(auth.VerifierCode);

                        Dispatcher.BeginInvoke(new Action <CopyClient>(AfterAuthenticate), copyClient);
                    }
                };

                Scope scope = new Scope()
                {
                    Profile = new ProfilePermission()
                    {
                        Read  = true,
                        Write = true
                    }
                };

                copyConfig = new Authentication.CopyAuth("http://copysdk", "cIAKv1kFCwXn2izGsMl8vZmfpfBcJSv1", "vNY1oLTr2WieLYxgCA6tDgdfCS1zTRA2IMzhmQLoQOS7nmIK", scope);

                await copyConfig.GetRequestTokenAsync();

                Oauth.Visibility           = Visibility.Visible;
                AuthenticateBtn.Visibility = Visibility.Collapsed;

                Oauth.GetVerifierCode(copyConfig.AuthCodeUri, new Uri(copyConfig.CallbackURL));
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Attempt to get and set an OAuth token with client id and secret
        /// </summary>
        public void Login(string clientId, string clientSecret)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new ApiException(400, "Missing required paramater clientId");
            }
            // Login as user if available
            if (!string.IsNullOrEmpty(this.Configuration.Username) &&
                !string.IsNullOrEmpty(this.Configuration.Password))
            {
                LoginAsUser(clientId, this.Configuration.Username, this.Configuration.Password);
                return;
            }
            // Must be logging in with id and secret
            if (string.IsNullOrEmpty(clientSecret))
            {
                throw new ApiException(400, "Missing required paramater clientSecret");
            }
            var token = Oauth.GetOauthToken("client_credentials",
                                            clientId,
                                            clientSecret: clientSecret);

            this.Configuration.AccessToken = token.AccessToken;
        }
        public async Task <String> getAuthorizationOauth()
        {
            Oauth oauth = await getAccessToken();

            return($"{oauth.token_type} {oauth.access_token}");
        }