예제 #1
0
        public void GenerateOAuth2HeaderTest_nullToken()
        {
            string token          = null;
            string expectedHeader = "";

            Assert.AreEqual(expectedHeader, OAuthUtil.GenerateOAuth2Header(token));
        }
예제 #2
0
        public void TestGenerateSignature()
        {
            String body   = "{ \"name\":\"andrea\", \"surname\":\"rizzini\" }";
            String method = "POST";
            String url    = "http://www.andrea.rizzini.com/simple_service";

            OAuthParameters oAuthParameters = new OAuthParameters();

            oAuthParameters.setOAuthConsumerKey(((OAuthAuthentication)ApiConfig.GetAuthentication()).ClientId);
            oAuthParameters.setOAuthNonce("NONCE");
            oAuthParameters.setOAuthTimestamp("TIMESTAMP");
            oAuthParameters.setOAuthSignatureMethod("RSA-SHA1");


            if (!string.IsNullOrEmpty(body))
            {
                String encodedHash = Util.Base64Encode(Util.Sha1Encode(body));
                oAuthParameters.setOAuthBodyHash(encodedHash);
            }

            String baseString = OAuthUtil.GetBaseString(url, method, oAuthParameters.getBaseParameters());

            Assert.AreEqual("POST&http%3A%2F%2Fwww.andrea.rizzini.com%2Fsimple_service&oauth_body_hash%3DapwbAT6IoMRmB9wE9K4fNHDsaMo%253D%26oauth_consumer_key%3DgVaoFbo86jmTfOB4NUyGKaAchVEU8ZVPalHQRLTxeaf750b6%2521414b543630362f426b4f6636415a5973656c33735661383d%26oauth_nonce%3DNONCE%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3DTIMESTAMP", baseString);

            String signature = OAuthUtil.RsaSign(baseString);

            Assert.AreEqual("CQJfOX6Yebd7KPPsG7cRopzt+4/QB+GiMQhgcFMw+ew2bWtBLj+t8i6mSe26eEVurxzF4mp0uvjXZzz8Ik5YLjP1byr0v+wsMmAQbWUTj4dO7k8W2+a4AISmKFfbSEUaDgBpPyCl72cL29+hoTNo/usD0EYpaX6P1Vo+EYLbZjK3ZJRtDSd8VZnjxKInUoNI8VvJuGgZ3u7nh5caXvVk6RlCbgwdVEKAv/BsfLSQEgc0/DCCKhX2ZnNOqJJ3FRS6s4bAbqYbui5ouWN5SGkcRaYPt7Fi8oTu561oNZ02HlAWL9m0fp8MK6ZDGQjkeC+zWeo/o0Gbc+/kKGPdOrCNFA==", signature);
            oAuthParameters.setOAuthSignature(signature);
        }
예제 #3
0
        public void GenerateOAuth2HeaderTest_nonEmptyToken()
        {
            string token          = "ADFWEB2324deoi34/";
            string expectedHeader = "Authorization: OAuth " + token;

            Assert.AreEqual(expectedHeader, OAuthUtil.GenerateOAuth2Header(token));
        }
예제 #4
0
 public AccountController()
 {
     string churchCode = GetRequestedChurchCode();
     Model = new ModelFactory<iServeDBProcedures>(new iServeDBDataContext(), GetCurrentUserID());
     OAuthHelper = new OAuthUtil(Config.BaseAPIUrl, churchCode, Config.ApiVersion, Config.F1LoginMethod, Config.ConsumerKey, Config.ConsumerSecret);
     PersonAPI = new PersonAPI(churchCode);
 }
예제 #5
0
        private void AuthenticateTwitter() // used for twitter
        {
            var requestTokenQuery = OAuthUtil.GetRequestTokenQuery();

            requestTokenQuery.RequestAsync(Social.TwitterSettings.RequestTokenUri, null);
            requestTokenQuery.QueryResponse += new EventHandler <WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
        }
예제 #6
0
        public static void Authorize(OAuth2Parameters parameters)
        {
            //parameters.RedirectUri = "urn:ietf:wg:oauth:2.0:oob";

            parameters.RedirectUri = "http://localhost:8080";
            string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            var listener = new HttpListener();

            listener.Prefixes.Add("http://localhost:8080/");
            listener.Start();
            var contextAsync = listener.GetContextAsync();

            System.Diagnostics.Process.Start(authorizationUrl);

            contextAsync.Wait();
            parameters.AccessCode = contextAsync.Result.Request.QueryString["code"];

            HttpListenerResponse response = contextAsync.Result.Response;
            // Construct a response.
            string responseString = "<HTML><head><script>window.open('', '_self', ''); /* bug fix chrome*/ window.close();</script></head></HTML>";

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            // You must close the output stream.
            output.Close();
            listener.Stop();

            //http://stackoverflow.com/questions/12077455/gdata-oauthutil-getaccesstoken-does-not-return-a-refresh-token-value
            OAuthUtil.GetAccessToken(parameters);
        }
예제 #7
0
        /// <summary>
        /// This console application demonstrates the usage of OAuth 2.0 with the Google Apps APIs.
        /// </summary>
        /// <param name="args">Command-line arguments: args[0] is
        /// the client ID, args[1] is the client secret, args[2] is domain name.
        /// </param>
        public static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Syntax: OAuth2Demo <client_id> <client_secret> <domain>");
            }
            else
            {
                clientId     = args[0];
                clientSecret = args[1];
                domain       = args[2];

                OAuth2Parameters parameters = new OAuth2Parameters()
                {
                    ClientId     = clientId,
                    ClientSecret = clientSecret,
                    RedirectUri  = redirectUri,
                    Scope        = scopes
                };

                string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
                Console.WriteLine("Authorize URI: " + url);
                parameters.AccessCode = Console.ReadLine();

                OAuthUtil.GetAccessToken(parameters);

                // Testing OAuth 2.0 with a Request-based library
                RunContactsSample(parameters);

                // Testing OAuth 2.0 with a Service-based library
                RunGroupsSample(parameters, domain);
            }
        }
        public static void InitAuthenticate()
        {
            string clientId     = GoogleDataSettings.Instance.OAuth2Data.client_id;
            string clientSecret = GoogleDataSettings.Instance.OAuth2Data.client_secret;
            string accessCode   = GoogleDataSettings.Instance._AccessCode;

            // OAuth2Parameters holds all the parameters related to OAuth 2.0.
            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.ClientId     = clientId;
            parameters.ClientSecret = clientSecret;
            parameters.RedirectUri  = REDIRECT_URI;

            // Retrieves the Authorization URL
            parameters.Scope      = SCOPE;
            parameters.AccessType = "offline";  // IMPORTANT and was missing in the original
            parameters.TokenType  = TOKEN_TYPE; // IMPORTANT and was missing in the original

            string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            Debug.Log(authorizationUrl);
            Debug.Log("Please visit the URL above to authorize your OAuth "
                      + "request token.  Once that is complete, type in your access code to "
                      + "continue...");

            parameters.AccessCode = accessCode;

            if (string.IsNullOrEmpty(parameters.AccessCode))
            {
                Application.OpenURL(authorizationUrl);
            }
        }
예제 #9
0
        public void newMethod()
        {
            string CLIENT_ID = "599831794378-85d0ai95jak2mobjp1h0p7n0d2bua8n3.apps.googleusercontent.com";

            string CLIENT_SECRET = "AlYRvFcwAILGyTMwYZz2veoJ";

            string SCOPE = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds";

            string REDIRECT_URI = "http://localhost:53278/uploadpage.aspx";// "urn:ietf:wg:oauth:2.0:oob";


            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.ClientId = CLIENT_ID;

            parameters.ClientSecret = CLIENT_SECRET;

            parameters.RedirectUri = REDIRECT_URI;

            parameters.Scope = SCOPE;
            Session["para"]  = parameters;
            string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            Response.Redirect(authorizationUrl);
        }
예제 #10
0
        public static string getAuthorizationURL(string clientId, string clientSecret)
        {
            OAuth2Parameters parameters = getOAuth2Parameters(clientId, clientSecret);
            string           authURL    = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            return(authURL);
        }
예제 #11
0
        public bool SignIn(string accessCode)
        {
            try
            {
                parameters            = GetRawOAuth2Parameters();
                parameters.AccessCode = accessCode;

                // 同期WebRequest通信が中で走る.
                OAuthUtil.GetAccessToken(parameters);

                SpreadsheetConnectorPrefs.accessTokenKey  = parameters.AccessToken;
                SpreadsheetConnectorPrefs.refreshTokenKey = parameters.RefreshToken;
                SpreadsheetConnectorPrefs.tokenExpiryKey  = parameters.TokenExpiry.ToString();

                service = CreateService(parameters);

                State = AuthenticationState.SignIn;
                return(true);
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                SignOut();
                return(false);
            }
        }
        public ActionResult SubmitAuthorize(string code)
        {
            string           REDIRECT_URI = "http://localhost:11551" + Url.Action("SubmitAuthorize", new { controller = "photoshop", area = "admin" });
            OAuth2Parameters parameters   = new OAuth2Parameters
            {
                ClientId     = CLIENT_ID,
                ClientSecret = CLIENT_SECRET,
                RedirectUri  = REDIRECT_URI,
                Scope        = SCOPE,
                AccessCode   = code
            };

            OAuthUtil.GetAccessToken(parameters);
            string accessToken = parameters.AccessToken;
            var    shet        = _context.GoogleSheetsSync.Find(Guid.Empty);

            if (shet == null)
            {
                shet = new GoogleSheetsSync()
                {
                    ID           = Guid.Empty,
                    Token        = accessToken,
                    RefreshToken = parameters.RefreshToken
                };
                _context.GoogleSheetsSync.Add(shet);
            }
            else
            {
                shet.Token        = accessToken;
                shet.RefreshToken = parameters.RefreshToken;
            }
            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #13
0
    private void GetUnauthorizedRequestToken(OAuthParameters parameters)
    {
        String requestTokenUrl = "https://www.google.com/accounts/OAuthGetRequestToken";
        Uri    requestUri      = new Uri(string.Format("{0}?scope={1}", requestTokenUrl, OAuthBase.EncodingPerRFC3986(parameters.Scope)));
        // callback is only needed when getting the request token
        bool callbackExists = false;

        if (!string.IsNullOrEmpty(parameters.Callback))
        {
            parameters.BaseProperties.Add(OAuthBase.OAuthCallbackKey, parameters.Callback);
            callbackExists = true;
        }
        string headers = OAuthUtil.GenerateHeader(requestUri, "GET", parameters);

        System.Net.WebRequest request = System.Net.WebRequest.Create(requestUri);
        request.Headers.Add(headers);
        System.Net.WebResponse response = request.GetResponse();
        string result = "";

        if (response != null)
        {
            System.IO.Stream       responseStream = response.GetResponseStream();
            System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream);
            result = reader.ReadToEnd();
        }
        if (callbackExists)
        {
            parameters.BaseProperties.Remove(OAuthBase.OAuthCallbackKey);
        }
        // split results and update parameters
        SortedDictionary <string, string> responseValues = OAuthBase.GetQueryParameters(result);

        parameters.Token       = responseValues[OAuthBase.OAuthTokenKey];
        parameters.TokenSecret = responseValues[OAuthBase.OAuthTokenSecretKey];
    }
        private void setAuthorizationToken()
        {
            OAuthUtil.GetAccessToken(oAuth2Parameters);
            string accessToken = oAuth2Parameters.AccessToken;

            Console.WriteLine("OAuth Access Token: " + accessToken);
        }
예제 #15
0
        public ActionResult AuthorizationCheck(GoogleAPIAccess model)
        {
            if (model.AccessCode == null)
            {
                ////////////////////////////////////////////////////////////////////////////
                // STEP 3: Get the Authorization URL
                ////////////////////////////////////////////////////////////////////////////

                // Get the authorization url.  The user of your application must visit
                // this url in order to authorize with Google.  If you are building a
                // browser-based application, you can redirect the user to the authorization
                // url.
                model._RedirectURIs              = "urn:ietf:wg:oauth:2.0:oob";
                ViewData["authorizationUrl"]     = OAuthUtil.CreateOAuth2AuthorizationUrl(model);
                model._RedirectURIs              = Url.Action("AuthorizationCheckAuto", "Configuration", new { }, "http");
                ViewData["authorizationUrlAuto"] = OAuthUtil.CreateOAuth2AuthorizationUrl(model);
                return(View(model));
            }

            ////////////////////////////////////////////////////////////////////////////
            // STEP 4: Get the Access Token
            ////////////////////////////////////////////////////////////////////////////

            // Once the user authorizes with Google, the request token can be exchanged
            // for a long-lived access token.  If you are building a browser-based
            // application, you should parse the incoming request token from the url and
            // set it in OAuthParameters before calling GetAccessToken().
            model._RedirectURIs = "urn:ietf:wg:oauth:2.0:oob";
            OAuthUtil.GetAccessToken(model);
            return(RedirectToAction("Index", model));
        }
        public static void FinishAuthenticate(GoogleSettings googleSettings)
        {
            try {
                OAuth2Parameters parameters = new OAuth2Parameters();
                parameters.ClientId     = googleSettings.authInfo.client_id;
                parameters.ClientSecret = googleSettings.authInfo.client_secret;
                parameters.RedirectUri  = googleSettings.authInfo.GetRedirectURI();

                parameters.Scope      = SCOPE;
                parameters.AccessType = "offline";  // IMPORTANT
                parameters.TokenType  = TOKEN_TYPE; // IMPORTANT

                parameters.AccessCode = googleSettings.accessCode;

                OAuthUtil.GetAccessToken(parameters);
                string accessToken  = parameters.AccessToken;
                string refreshToken = parameters.RefreshToken;
                //Debug.Log("OAuth Access Token: " + accessToken + "\n");
                //Debug.Log("OAuth Refresh Token: " + refreshToken + "\n");

                googleSettings.refreshToken = refreshToken;
                googleSettings.accessToken  = accessToken;
            }
            catch (Exception e) {
                // To display the error message with EditorGUI.Dialogue, we throw it again.
                throw new Exception(e.Message);
            }
        }
예제 #17
0
        private void GetAccessCode(object sender, NavigationEventArgs e)
        {
            mshtml.IHTMLDocument2 doc = LoginBrowser.Document as mshtml.IHTMLDocument2;
            string accessCode         = doc.title;

            if (accessCode.Substring(0, 7) == "Success")
            {
                accessCode            = accessCode.Remove(0, 13);
                parameters.AccessCode = accessCode;// Key.Text;
                OAuthUtil.GetAccessToken(parameters);
                string accessToken = parameters.AccessToken;

                GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "BoardGameStats", parameters);
                service.RequestFactory = requestFactory;

                if (service != null)
                {
                    DialogResult = true;
                }
                else
                {
                    DialogResult = false;
                }
            }
        }
예제 #18
0
        public void SignOn(string status, int state)
        {
            var param = new Dictionary <string, string>();

            param["realm"] = "yahooapis.com";
            param["oauth_consumer_key"]     = FetchReqData.ConsummerKey;
            param["oauth_nonce"]            = OAuthUtil.GenerateNonce();
            param["oauth_signature_method"] = "PLAINTEXT";
            param["oauth_timestamp"]        = OAuthUtil.GenerateTimeStamp();
            param["oauth_token"]            = FetchReqData.OauthToken;
            param["oauth_version"]          = "1.0";
            param["oauth_signature"]        = FetchReqData.ConsummerSecret + "%26" + FetchReqData.OauthTokenSecret;
            OauthHeader = MakeRequestHeader(param);

            var url = new StringBuilder(CommonConst.URL_YM_SESSION);

            url.Append("?notifyServerToken=1");

            WebRequest request = WebRequest.Create(url.ToString());

            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("Authorization", OauthHeader);

            var data   = MakeJsonData(status, state);
            var result = HttpUtil.SendPostReq(request, data, true);
            var temp   = StringUtil.Split(result, "<QuangPB>");

            Cookie = GetCookie(temp[0].Trim());
            GetOtherInfoOfSignOn(temp[1].Trim());
        }
 public void Second(string someAccessCode)
 {
     // I want to reuse the above OAuth2Parameters parameters here:
     parameters.AccessCode = someAccessCode;
     OAuthUtil.GetAccessToken(parameters);
     string accessToken = parameters.AccessToken;
 }
예제 #20
0
        public static OAuth2Parameters Authorize()
        {
            var parameters = new OAuth2Parameters
            {
                ClientId     = ConfigurationManager.AppSettings.Get("Google-ClientID"),
                ClientSecret = ConfigurationManager.AppSettings.Get("Google-ClientSecret"),
                Scope        = "https://spreadsheets.google.com/feeds",
                RedirectUri  = "urn:ietf:wg:oauth:2.0:oob" //installed applications
            };

            var authUri = new Uri(OAuthUtil.CreateOAuth2AuthorizationUrl(parameters));

            using (var login = new GoogleLogin(authUri))
            {
                if (login.ShowDialog() != DialogResult.OK)
                {
                    return(null);
                }
                parameters.AccessCode = login.AccessCode;
            }

            try
            {
                OAuthUtil.GetAccessToken(parameters);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }

            return(parameters);
        }
예제 #21
0
        public JsonResult GetGmailAuthorizationCode(bool isTask, bool isContact)
        {
            string scope = string.Empty;

            if (isTask)
            {
                scope = "https://www.googleapis.com/auth/tasks";
            }
            else if (isContact)
            {
                scope = "https://www.googleapis.com/auth/contacts.readonly";
            }
            else
            {
                scope = "https://www.googleapis.com/auth/calendar";
            }
            OAuth2Parameters parameters = new OAuth2Parameters()
            {
                //Client
                ClientId     = ClientCredentials.ClientID,
                ClientSecret = ClientCredentials.ClientSecret,
                RedirectUri  = "urn:ietf:wg:oauth:2.0:oob",
                //  Scope = "https://www.googleapis.com/auth/tasks",
                Scope = scope,
            };

            //User clicks this auth url and will then be sent to your redirect url with a code parameter
            var authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
            //string retError = "";
            string retJSON = "";

            retJSON = JsonConvert.SerializeObject(authorizationUrl);
            return(Json(retJSON, JsonRequestBehavior.AllowGet));
        }
        public void Connect()
        {
            if (_parameters.AccessCode == null)
            {
                throw new InvalidOperationException("No access code set.");
            }


            ////////////////////////////////////////////////////////////////////////////
            // STEP 4: Get the Access Token
            ////////////////////////////////////////////////////////////////////////////

            // Once the user authorizes with Google, the request token can be exchanged
            // for a long-lived access token.  If you are building a browser-based
            // application, you should parse the incoming request token from the url and
            // set it in OAuthParameters before calling GetAccessToken().
            OAuthUtil.GetAccessToken(_parameters);
            string accessToken = _parameters.AccessToken;

            Console.WriteLine("OAuth Access Token: " + accessToken);

            ////////////////////////////////////////////////////////////////////////////
            // STEP 5: Make an OAuth authorized request to Google
            ////////////////////////////////////////////////////////////////////////////

            // Initialize the variables needed to make the request
            GOAuth2RequestFactory requestFactory =
                new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", _parameters);

            _service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
            _service.RequestFactory = requestFactory;

            // Make the request to Google
            // See other portions of this guide for code to put here...
        }
예제 #23
0
        private void NGAMail()
        {
            //One time Initialization across the entire session required
            //if (authorizationUrl == null || authorizationUrl == string.Empty)
            //{
            string           CLIENT_ID     = "284081438460-sdg3dn9tt80huceeb9v4n833n97lmtlu.apps.googleusercontent.com";
            string           CLIENT_SECRET = "HNb2txJ2QpK0amd4IR7HAxZK";
            string           SCOPE         = "https://spreadsheets.google.com/feeds";
            string           REDIRECT_URI  = "urn:ietf:wg:oauth:2.0:oob";
            OAuth2Parameters parameters    = new OAuth2Parameters();

            parameters.ClientId     = CLIENT_ID;
            parameters.ClientSecret = CLIENT_SECRET;
            parameters.RedirectUri  = REDIRECT_URI;
            parameters.Scope        = SCOPE;
            authorizationUrl        = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            if (InputBox("AccessCode", "Input AccessCode from Browser", ref authorizationUrl) == DialogResult.OK)
            {
                parameters.AccessCode = authorizationUrl;
            }
            else
            {
                MessageBox.Show("Invallid Access Code!");
                btnConnectJenkins.Enabled = true;
                return;
            }

            OAuthUtil.GetAccessToken(parameters);
            GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "AlmJenkinsIntegration", parameters);

            spreadsheetsService.RequestFactory = requestFactory;
            //}
        }
예제 #24
0
        private void MenuItemSignIn_Click(object sender, EventArgs e)
        {
            var requestTokenQuery = OAuthUtil.GetRequestTokenQuery();

            requestTokenQuery.RequestAsync(AppSettings.RequestTokenUri, null);
            requestTokenQuery.QueryResponse += new EventHandler <WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
        }
예제 #25
0
        /// <summary>
        /// Takes an existing httpwebrequest and modifies its headers according to
        /// the authentication system used.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public override void ApplyAuthenticationToRequest(HttpWebRequest request)
        {
            string oauthHeader = OAuthUtil.GenerateAuthorizationHeader(
                request.RequestUri, ConsumerKey, ConsumerSecret, null, null, request.Method);

            request.Headers[HttpRequestHeader.Authorization] = oauthHeader;
        }
예제 #26
0
        public void TestGenerateSignature()
        {
            String body   = "{ \"name\":\"andrea\", \"surname\":\"rizzini\" }";
            String method = "POST";
            String url    = "http://www.andrea.rizzini.com/simple_service";

            OAuthParameters oAuthParameters = new OAuthParameters();

            oAuthParameters.setOAuthConsumerKey(((OAuthAuthentication)ApiConfig.GetAuthentication()).ClientId);
            oAuthParameters.setOAuthNonce("NONCE");
            oAuthParameters.setOAuthTimestamp("TIMESTAMP");
            oAuthParameters.setOAuthSignatureMethod("RSA-SHA256");


            if (!string.IsNullOrEmpty(body))
            {
                String encodedHash = Util.Base64Encode(Util.Sha1Encode(body));
                oAuthParameters.setOAuthBodyHash(encodedHash);
            }

            String baseString = OAuthUtil.GetBaseString(url, method, oAuthParameters.getBaseParameters());

            Assert.AreEqual("POST&http%3A%2F%2Fwww.andrea.rizzini.com%2Fsimple_service&oauth_body_hash%3DapwbAT6IoMRmB9wE9K4fNHDsaMo%253D%26oauth_consumer_key%3DL5BsiPgaF-O3qA36znUATgQXwJB6MRoMSdhjd7wt50c97279%252150596e52466e3966546d434b7354584c4975693238513d3d%26oauth_nonce%3DNONCE%26oauth_signature_method%3DRSA-SHA256%26oauth_timestamp%3DTIMESTAMP", baseString);

            String signature = OAuthUtil.RsaSign(baseString);

            //Assert.AreEqual ("QcjTdnu6CQETgu3czDyURblLsYGIWgsWbnhENB0U0EqgXtoc50lTCvpfPQHT8pPBJ6y6USUgTxShcDXDzDrM4FWMkz0FnQtpTyo4c0ZOInrn9DwDKEOgFtw3BpHxJ1jZ5NSfGwOLXdUThWvS7JylYHod0u4D0381/9y/PkataSX5AdSBEZAT943AIrwHEVWKaGKzt6ABW+GA7GboyhGUWxEVZWXZwT1WURHtUwCOsSbEGPiiURs2+HzOkvLs4tkuMGCNF/9tkEnEcjOHefN1mSVLiv2poJQJQQLps1iOk8v4MwSsnZ8RxlEUET690R0TZ1FhEBJJ25CmwarsUpI3DQ==", signature);
            oAuthParameters.setOAuthSignature(signature);
        }
예제 #27
0
    public void GetAccessToken()
    {
        /*
         * https://github.com/kimsama/Unity-QuickSheet/blob/50dfaed0397c511ac9da9ee42f64143b3a63e02e/Assets/QuickSheet/GDataPlugin/Editor/GDataDB/GDataDB/Impl/GDataDBRequestFactory.cs#L104-L122
         */
        Init();
        OAuth2Parameters parameters = new OAuth2Parameters();

        parameters.ClientId     = CLIENT_ID;
        parameters.ClientSecret = CLIENT_SECRET;
        parameters.RedirectUri  = REDIRECT_URI;

        parameters.Scope      = SCOPE;
        parameters.AccessType = "offline";  // IMPORTANT
        parameters.TokenType  = TOKEN_TYPE; // IMPORTANT

        parameters.AccessCode = ACCESS_CODE;

        OAuthUtil.GetAccessToken(parameters);
        OAuthUtil.RefreshAccessToken(parameters);

        ACCESS_TOKEN  = parameters.AccessToken;
        REFRESH_TOKEN = parameters.RefreshToken;

        EditorUtility.SetDirty(this);
    }
예제 #28
0
    void GetAccessCode()
    {
        // OAuth2Parameters holds all the parameters related to OAuth 2.0.
        OAuth2Parameters parameters = new OAuth2Parameters();

        parameters.ClientId = CLIENT_ID;

        parameters.ClientSecret = CLIENT_SECRET;

        parameters.RedirectUri = REDIRECT_URI;

        // Get the Authorization URL
        parameters.Scope = SCOPE;

        parameters.AccessType = "offline";         // IMPORTANT and was missing in the original

        parameters.TokenType = TOKEN_TYPE;         // IMPORTANT and was missing in the original

        // Authorization url.

        string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

        Debug.Log(authorizationUrl);
        Debug.Log("Please visit the URL above to authorize your OAuth "
                  + "request token.  Once that is complete, type in your access code to "
                  + "continue...");

        parameters.AccessCode = accessCode;

        if (parameters.AccessCode == "")
        {
            Debug.LogWarning("Access code is blank!");
            EditorUtility.ClearProgressBar();
            Application.OpenURL(authorizationUrl);
            return;
        }

        Debug.Log("Get access token.");

        // Get the Access Token
        try{
            OAuthUtil.GetAccessToken(parameters);
            string accessToken  = parameters.AccessToken;
            string refreshToken = parameters.RefreshToken;
            Debug.Log("OAuth Access Token: " + accessToken + "\n");
            ACCESS_TOKEN = accessToken;
            Debug.Log("OAuth Refresh Token: " + refreshToken + "\n");
            REFRESH_TOKEN = refreshToken;
            PlayerPrefs.SetString(PREF_ACCESS_CODE, accessCode);
            PlayerPrefs.Save();
            DownloadToJson();
        }
        catch (System.Exception e)
        {
            Debug.LogError(e.ToString());
            EditorUtility.ClearProgressBar();
            Application.OpenURL(authorizationUrl);
            return;
        }
    }
예제 #29
0
        private void AutenticaChangeColor()
        {
            string corlor_name = string.Empty;

            if (isAlreadyLoggedIn())
            {
                userLoggedIn();

                switch (CorSelecionada)
                {
                case MicrosoftColors.Blue: corlor_name = "Azul"; break;

                case MicrosoftColors.Green: corlor_name = "Verde"; break;

                case MicrosoftColors.Orange: corlor_name = "Amarelo"; break;

                case MicrosoftColors.Red: corlor_name = "Vermelho"; break;
                }
                ChangeColor(CorSelecionada, userScreenName, String.Format(this.strMensagemTwitte, corlor_name));
            }
            else
            {
                loginBrowserControl.Visibility = System.Windows.Visibility.Visible;
                ContentPanel.Visibility        = System.Windows.Visibility.Collapsed;

                var requestTokenQuery = OAuthUtil.GetRequestTokenQuery();
                requestTokenQuery.RequestAsync(TwitterSettings.RequestTokenUri, null);
                requestTokenQuery.QueryResponse += new EventHandler <WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
            }
        }
        public static void FinishAuthenticate(GoogleDataSettings settings)
        {
            try
            {
                OAuth2Parameters parameters = new OAuth2Parameters()
                {
                    ClientId     = settings.OAuth2Data.client_id,
                    ClientSecret = settings.OAuth2Data.client_secret,
                    RedirectUri  = REDIRECT_URI,

                    Scope      = SCOPE,
                    AccessType = "offline",  // IMPORTANT
                    TokenType  = TOKEN_TYPE, // IMPORTANT

                    AccessCode = settings._AccessCode
                };
                OAuthUtil.GetAccessToken(parameters);
                string accessToken  = parameters.AccessToken;
                string refreshToken = parameters.RefreshToken;
                //Debug.Log("OAuth Access Token: " + accessToken + "\n");
                //Debug.Log("OAuth Refresh Token: " + refreshToken + "\n");

                settings._RefreshToken = refreshToken;
                settings._AccessToken  = accessToken;
            }
            catch (Exception e)
            {
                // To display the error message with EditorGUI.Dialogue, we throw it again.
                throw new Exception(e.Message);
            }
        }
예제 #31
0
        public bool ShowAuthorizationDialog(bool isModal)
        {
            logger.Debug("ShowAuthorizationDialog {0}", isModal);
            string         sAuthorizationURL = OAuthUtil.CreateOAuth2AuthorizationUrl(AuthParams);
            GoogleAuthForm fAuthForm         = new GoogleAuthForm();

            fAuthForm.Url = sAuthorizationURL;
            if (isModal)
            {
                fAuthForm.ShowDialog();
            }
            else
            {
                fAuthForm.Show();
            }
            AuthResult arAuthResult = fAuthForm.Result ?? new AuthResult()
            {
                Result = ResultType.Denied, Value = string.Empty
            };

            logger.Info("Authorization Result={0}, Value={1}", arAuthResult.Result, arAuthResult.Value);

            if (arAuthResult.Result == ResultType.Success)
            {
                AuthParams.AccessCode = arAuthResult.Value;
                OAuthUtil.GetAccessToken(AuthParams);

                SaveAuthParams();

                return(true);
            }

            return(false);
        }
예제 #32
0
        public void GenerateTimeStampTest()
        {
            // Generate a Timestamp, and fetch the creation time of the timestamp for later comparison
            var util = new OAuthUtil();
            var srcTime = DateTime.UtcNow;
            string timestamp = util.GenerateTimeStamp();

            // Ensure that the generated timestamp is a whole number
            long unixTime;
            Assert.That(long.TryParse(timestamp, out unixTime), Is.True);

            // Convert the UNIX timestamp to a .NET DateTime
            var parsedTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(unixTime);
            TimeSpan timeDifference = parsedTime - srcTime;

            // Check whether the timestamp represents the current time
            Assert.That((long)Math.Abs(timeDifference.TotalSeconds), Is.EqualTo(0));
        }
예제 #33
0
 public AccountController(IModelFactory<iServeDBProcedures> modelFactory, PersonAPI personAPI, OAuthUtil oauthHelper)
 {
     Model = modelFactory;
     PersonAPI = PersonAPI;
     OAuthHelper = oauthHelper;
 }