Beispiel #1
0
        // This button allows you to relinquish the access token. This is the equivalent of
        // logging out.
        protected void btnInvalideToken_Click(object sender, EventArgs e)
        {
            // Build the request to relinquish the access
            // token
            var request = new RestRequest("OAuth/InvalidateToken", Method.POST);

            if (oobCheckBox.Checked == false)
            {
                m_Client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    m_ConsumerKey,
                    m_ConsumerSecret,
                    m_oAuthAccessToken,
                    m_oAuthAccessTokenSecret,
                    m_sessionHandle);
            }
            else
            {
                string verifier = getVerifier();

                //Use PIN to request access token for users account
                m_Client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    m_ConsumerKey,
                    m_ConsumerSecret,
                    m_oAuthAccessToken,
                    m_oAuthAccessTokenSecret,
                    verifier,
                    m_sessionHandle);
            }

            // execute the request to relinquish token
            var response = m_Client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                m_Client        = null;
                logOutput.Text += ("</br>Oops! Something went wrong - couldn't log out of your Autodesk account" + "</br>" + "-----------------------" + "</br>");

                btnGetAccessToken.Enabled = false;
                BtnRefreshToken.Enabled   = false;
                btnInvalideToken.Enabled  = false;
                txtVerifier.Text          = "";
                return;
            }
            else
            {
                logOutput.Text += ("Logout successful!" + "</br>" + "-----------------------" + "</br>");
            }



            // Disable all controls except the out of band radio button and the Request Token button if the request
            // to relinquish the access token is successful.

            btnGetAccessToken.Enabled = false;
            BtnRefreshToken.Enabled   = false;
            btnInvalideToken.Enabled  = false;
            txtVerifier.Text          = "";
        }
Beispiel #2
0
        // Logout OAuth service, i.e. Invalidate Token
        public async Task <bool> DoLogoutAsync()
        {
            try
            {
                RestRequest invalidateRequest = new RestRequest
                {
                    Resource = "OAuth/InvalidateToken",
                };

                _client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    ConsumerKey,
                    ConsumerSecret,
                    AccessToken,
                    AccessTokenSecret,
                    SessionHandle);

                IRestResponse accessTokenResponse = await _client.ExecuteAsync(
                    invalidateRequest);

                var invalidateTokenResponseValues =
                    ParseResponse(accessTokenResponse.Content);

                if (CheckError(invalidateTokenResponseValues))
                {
                    string problem = invalidateTokenResponseValues["xoauth_problem"];
                    string msg     = invalidateTokenResponseValues["oauth_error_message"];

                    OnErrorEvent(problem, msg);

                    return(false);
                }

                // Clear resources

                AccessToken = string.Empty;

                AccessTokenSecret = string.Empty;

                TokenExpire = 0;

                SessionHandle = string.Empty;

                SessionExpire = 0;

                UserName = string.Empty;

                UserGUID = string.Empty;

                return(true);
            }
            catch (Exception ex)
            {
                OnErrorEvent(ex.ToString(), ex.Message);

                return(false);
            }
        }
Beispiel #3
0
        //- If we do not want to use the service anymore then
        //- the best thing is to log out, i.e. invalidate the tokens we got
        public static async Task <bool> InvalidateToken()
        {
            try {
                if (_restClient == null)
                {
                    _restClient = new RestClient(UserSettings.OAUTH_HOST);
                }

                LogInfo("Initializing to release Access Tokens");
                var request = new RestRequest(UserSettings.OAUTH_INVALIDATETOKEN, Method.POST);
                _restClient.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    UserSettings.CONSUMER_KEY, UserSettings.CONSUMER_SECRET,
                    Properties.Settings.Default.oauth_token, Properties.Settings.Default.oauth_token_secret,
                    Properties.Settings.Default.oauth_session_handle
                    );
                Log(UserSettings.OAUTH_INVALIDATETOKEN + " request sent", "Request");
                //var response =_restClient.Execute (request) ;
                var response = await _restClient.ExecuteTaskAsync(request);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    LogError("Failure! HTTP request did not work! Maybe you are having a connection problem?");
                    return(false);
                }

                // If Invalidate was successful, we will not get back any data
                if (response.Content.Length == 0)
                {
                    Properties.Settings.Default.oauth_token          = "";
                    Properties.Settings.Default.oauth_token_secret   = "";
                    Properties.Settings.Default.oauth_session_handle = "";
                    Properties.Settings.Default.x_oauth_user_name    = "";
                    Properties.Settings.Default.x_oauth_user_guid    = "";
                    Properties.Settings.Default.Save();
                    Log("Success! Access Tokens released", "Response");
                }
                else
                {
                    var accessToken = HttpUtility.ParseQueryString(response.Content);
                    if (accessToken.AllKeys.Contains("xoauth_problem"))
                    {
                        LogError("Failure! " + accessToken ["xoauth_problem"] + ": " + accessToken ["oauth_error_message"]);
                    }
                    else
                    {
                        LogError("Failure! Could not log out!");
                    }
                    return(false);
                }
                return(true);
            } catch (Exception ex) {
                LogError("Exception: " + ex.Message);
                return(false);
            }
        }
Beispiel #4
0
        public OAuthToken RenewAccessToken(OAuthToken accessToken)
        {
            var client = new RestClient(_baseUrl)
            {
                Authenticator =
                    OAuth1Authenticator.ForAccessTokenRefresh(ConsumerKey, ConsumerSecret.To <string>(), accessToken.Token, accessToken.Secret, null)
            };

            var response = ExecuteRequest(client, new RestRequest("oauth/renew_access_token"));

            if (response.ResponseStatus != ResponseStatus.Completed || response.StatusCode != HttpStatusCode.OK)
            {
                throw new ETradeAuthorizationRenewFailed(
                          LocalizedStrings.Str3349Params.Put(response.StatusCode + ": " + response.StatusDescription));
            }

            var qs = HttpUtility.ParseQueryString(response.Content);

            var newToken = qs["oauth_token"];

            return(newToken == null ? accessToken : new OAuthToken(ConsumerKey, newToken, qs["oauth_token_secret"]));
        }
        // This button allows you to relinquish the access token. This is the equivalent of
        // logging out.
        private void invalidateButton_Click(object sender, RoutedEventArgs e)
        {
            // Build the request to relinquish the access
            // token
            var request = new RestRequest("OAuth/InvalidateToken", Method.POST);

            if (oobCheckBox.IsChecked == false)
            {
                m_Client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    m_ConsumerKey,
                    m_ConsumerSecret,
                    m_oAuthAccessToken,
                    m_oAuthAccessTokenSecret,
                    m_sessionHandle);
            }
            else
            {
                m_strPIN = pinTxt.Text;
                string strPIN = m_strPIN.Trim();
                if (strPIN == "")
                {
                    logOutput.AppendText("\nInvalid PIN." + "\n" + "-----------------------" + "\n");
                    m_Client = null;
                    authorizeTokenBtn.IsEnabled = false;

                    acssTokenBtn.IsEnabled     = false;
                    refreshTokenBtn.IsEnabled  = false;
                    invalidateButton.IsEnabled = false;
                    pinTxt.Text = "";
                    return;
                }
                //Use PIN to request access token for users account
                m_Client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    m_ConsumerKey,
                    m_ConsumerSecret,
                    m_oAuthAccessToken,
                    m_oAuthAccessTokenSecret,
                    strPIN,
                    m_sessionHandle);
            }

            // execute the request to relinquish token
            var response = m_Client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                m_Client = null;
                logOutput.AppendText("\nOops! Something went wrong - couldn't log out of your Autodesk account" + "\n" + "-----------------------" + "\n");
                authorizeTokenBtn.IsEnabled = false;

                acssTokenBtn.IsEnabled     = false;
                refreshTokenBtn.IsEnabled  = false;
                invalidateButton.IsEnabled = false;
                pinTxt.Text = "";
                return;
            }
            else
            {
                logOutput.AppendText("Logout successful!" + "\n" + "-----------------------" + "\n");
            }



            // Disable all controls except the out of band radio button and the Request Token button if the request
            // to relinquish the access token is successful.
            authorizeTokenBtn.IsEnabled = false;

            acssTokenBtn.IsEnabled     = false;
            refreshTokenBtn.IsEnabled  = false;
            invalidateButton.IsEnabled = false;
            pinTxt.Text = "";
        }
        // Get a fresh access token
        private void refreshTokenBtn_Click(object sender, RoutedEventArgs e)
        {
            // Build the HTTP request to obtain a fresh access token
            var request = new RestRequest("OAuth/AccessToken", Method.POST);

            if (oobCheckBox.IsChecked == false)
            {
                m_Client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    m_ConsumerKey,
                    m_ConsumerSecret,
                    m_oAuthAccessToken,
                    m_oAuthAccessTokenSecret,
                    m_sessionHandle);
            }
            else
            {
                m_strPIN = pinTxt.Text;
                string strPIN = m_strPIN.Trim();
                if (strPIN == "")
                {
                    logOutput.AppendText("\nInvalid PIN." + "\n" + "-----------------------" + "\n");
                    m_Client = null;
                    authorizeTokenBtn.IsEnabled = false;

                    acssTokenBtn.IsEnabled     = false;
                    refreshTokenBtn.IsEnabled  = false;
                    invalidateButton.IsEnabled = false;
                    pinTxt.Text = "";
                    return;
                }

                //Use PIN to request access token for users account

                m_Client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    m_ConsumerKey,
                    m_ConsumerSecret,
                    m_oAuthAccessToken,
                    m_oAuthAccessTokenSecret,
                    strPIN,
                    m_sessionHandle);
            }


            var response = m_Client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                m_Client = null;
                logOutput.AppendText("\nOops! Something went wrong - couldn't get access token from your Autodesk account" + "\n" + "-----------------------" + "\n");
                authorizeTokenBtn.IsEnabled = false;

                acssTokenBtn.IsEnabled     = false;
                refreshTokenBtn.IsEnabled  = false;
                invalidateButton.IsEnabled = false;
                pinTxt.Text = "";
                return;
            }
            else
            {
                // The request for a fresh access token was successful. Store the new
                // access token, secret and session handle.
                var qs = HttpUtility.ParseQueryString(response.Content);
                m_oAuthAccessToken       = qs["oauth_token"];
                m_oAuthAccessTokenSecret = qs["oauth_token_secret"];
                var x_oauth_user_name   = qs["x_oauth_user_name"];
                var x_oauth_user_guid   = qs["x_oauth_user_guid"];
                var x_scope             = qs["x_scope"];
                var xoauth_problem      = qs["xoauth_problem"];
                var oauth_error_message = qs["oauth_error_message"];
                m_sessionHandle = qs["oauth_session_handle"];
            }

            var responseNamedCollection = HttpUtility.ParseQueryString(response.Content);

            string outputString = "";

            foreach (string key in responseNamedCollection.AllKeys)
            {
                outputString += key + "=" + responseNamedCollection[key] + "\n";
            }

            //Output response log
            logOutput.AppendText("Refresh Access Token Response:\n" + outputString + "-----------------------" + "\n");
        }
Beispiel #7
0
        // To refresh an existing, not expired token, it's similar to
        // requesting an access token but with the additional
        // session handle retrieved from the initial access token reply
        public async Task <bool> DoRefreshAsync()
        {
            try
            {
                RestRequest accessTokenRequest = new RestRequest
                {
                    Resource = "OAuth/AccessToken",
                    Method   = Method.POST,
                };

                _client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    ConsumerKey,
                    ConsumerSecret,
                    AccessToken,
                    AccessTokenSecret,
                    SessionHandle);

                IRestResponse accessTokenResponse = await _client.ExecuteAsync(
                    accessTokenRequest);

                var accessTokenResponseValues =
                    ParseResponse(accessTokenResponse.Content);

                if (CheckError(accessTokenResponseValues))
                {
                    string problem = accessTokenResponseValues["xoauth_problem"];
                    string msg     = accessTokenResponseValues["oauth_error_message"];

                    OnErrorEvent(problem, msg);

                    return(false);
                }

                // Parsing reply components

                AccessToken =
                    accessTokenResponseValues["oauth_token"];

                AccessTokenSecret =
                    accessTokenResponseValues["oauth_token_secret"];

                TokenExpire = double.Parse(
                    accessTokenResponseValues["oauth_expires_in"]);

                SessionHandle =
                    accessTokenResponseValues["oauth_session_handle"];

                SessionExpire = double.Parse(
                    accessTokenResponseValues["oauth_authorization_expires_in"]);

                UserName =
                    accessTokenResponseValues["x_oauth_user_name"];

                UserGUID =
                    accessTokenResponseValues["x_oauth_user_guid"];

                return(true);
            }
            catch (Exception ex)
            {
                OnErrorEvent(ex.ToString(), ex.Message);

                return(false);
            }
        }
Beispiel #8
0
        // Get a fresh access token
        protected void BtnRefreshToken_Click(object sender, EventArgs e)
        {
            // Build the HTTP request to obtain a fresh access token
            var request = new RestRequest("OAuth/AccessToken", Method.POST);

            if (oobCheckBox.Checked == false)
            {
                m_Client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    m_ConsumerKey,
                    m_ConsumerSecret,
                    m_oAuthAccessToken,
                    m_oAuthAccessTokenSecret,
                    m_sessionHandle);
            }
            else
            {
                string verifier = getVerifier();

                //Use PIN to request access token for users account

                m_Client.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                    m_ConsumerKey,
                    m_ConsumerSecret,
                    m_oAuthAccessToken,
                    m_oAuthAccessTokenSecret,
                    verifier,
                    m_sessionHandle);
            }


            var response = m_Client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                m_Client        = null;
                logOutput.Text += ("</br>Oops! Something went wrong - couldn't get access token from your Autodesk account" + "</br>" + "-----------------------" + "</br>");

                btnGetAccessToken.Enabled = false;
                BtnRefreshToken.Enabled   = false;
                btnInvalideToken.Enabled  = false;
                txtVerifier.Text          = "";
                return;
            }
            else
            {
                // The request for a fresh access token was successful. Store the new
                // access token, secret and session handle.
                var qs = HttpUtility.ParseQueryString(response.Content);
                m_oAuthAccessToken       = qs["oauth_token"];
                m_oAuthAccessTokenSecret = qs["oauth_token_secret"];
                var x_oauth_user_name   = qs["x_oauth_user_name"];
                var x_oauth_user_guid   = qs["x_oauth_user_guid"];
                var x_scope             = qs["x_scope"];
                var xoauth_problem      = qs["xoauth_problem"];
                var oauth_error_message = qs["oauth_error_message"];
                m_sessionHandle = qs["oauth_session_handle"];
            }

            var responseNamedCollection = HttpUtility.ParseQueryString(response.Content);

            string outputString = "";

            foreach (string key in responseNamedCollection.AllKeys)
            {
                outputString += key + "=" + responseNamedCollection[key] + "</br>";
            }

            //Output response log
            logOutput.Text += ("Refresh Access Token Response:</br>" + outputString + "-----------------------" + "</br>");
        }
Beispiel #9
0
        //- Third leg: The third step is to authenticate using the request tokens
        //- Once you get the access token and access token secret you need to use those to make your further REST calls
        //- Same in case of refreshing the access tokens or invalidating the current session. To do that we need to pass
        //- in the acccess token and access token secret as the accessToken and tokenSecret parameter of the
        //- [AdskRESTful URLRequestForPath] function
        public static async Task <bool> AccessToken(bool refresh, string PIN)
        {
            try {
                if (_restClient == null)
                {
                    _restClient = new RestClient(UserSettings.OAUTH_HOST);
                }
                var request = new RestRequest(UserSettings.OAUTH_ACCESSTOKEN, Method.POST);

                // If we already got access tokens and now just try to refresh
                // them then we need to provide the session handle
                if (refresh)
                {
                    LogInfo("Refreshing Access Tokens");
                    if (Properties.Settings.Default.oauth_session_handle.Length == 0)
                    {
                        return(false);
                    }
                    if (isOOB)
                    {
                        _restClient.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                            UserSettings.CONSUMER_KEY, UserSettings.CONSUMER_SECRET,
                            Properties.Settings.Default.oauth_token, Properties.Settings.Default.oauth_token_secret,
                            PIN, Properties.Settings.Default.oauth_session_handle
                            );
                    }
                    else
                    {
                        _restClient.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                            UserSettings.CONSUMER_KEY, UserSettings.CONSUMER_SECRET,
                            Properties.Settings.Default.oauth_token, Properties.Settings.Default.oauth_token_secret,
                            Properties.Settings.Default.oauth_session_handle
                            );
                    }
                }
                else
                {
                    LogInfo("Acquiring new Access Tokens");
                    if (Properties.Settings.Default.oauth_token.Length == 0)
                    {
                        return(false);
                    }
                    if (isOOB)
                    {
                        // Use PIN to request access token for users account for an out of band request.
                        _restClient.Authenticator = OAuth1Authenticator.ForAccessToken(
                            UserSettings.CONSUMER_KEY, UserSettings.CONSUMER_SECRET,
                            Properties.Settings.Default.oauth_token, Properties.Settings.Default.oauth_token_secret,
                            PIN
                            );
                    }
                    else
                    {
                        _restClient.Authenticator = OAuth1Authenticator.ForAccessToken(
                            UserSettings.CONSUMER_KEY, UserSettings.CONSUMER_SECRET,
                            Properties.Settings.Default.oauth_token, Properties.Settings.Default.oauth_token_secret
                            );
                    }
                }

                Properties.Settings.Default.oauth_token          = "";
                Properties.Settings.Default.oauth_token_secret   = "";
                Properties.Settings.Default.oauth_session_handle = "";
                Properties.Settings.Default.x_oauth_user_name    = "";
                Properties.Settings.Default.x_oauth_user_guid    = "";
                Properties.Settings.Default.Save();

                Log(UserSettings.OAUTH_ACCESSTOKEN + " request sent", "Request");
                //var response =_restClient.Execute (request) ;
                var response = await _restClient.ExecuteTaskAsync(request);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    LogError("Failure! HTTP request did not work! Maybe you are having a connection problem?");
                    return(false);
                }

                // The HTTP request succeeded. Get the request token and associated parameters.
                var accessToken = HttpUtility.ParseQueryString(response.Content);
                if (accessToken.AllKeys.Contains("xoauth_problem"))
                {
                    LogError("Failure! " + accessToken ["xoauth_problem"] + ": " + accessToken ["oauth_error_message"]);
                    return(false);
                }
                if (accessToken.Count < 3 || accessToken ["oauth_session_handle"] == null)
                {
                    if (refresh)
                    {
                        LogError("Failure! Could not refresh Access Tokens!");
                    }
                    else
                    {
                        LogError("Failure! Could not get Access Tokens!");
                    }
                    return(false);
                }
                if (refresh)
                {
                    Log("Success! Access Tokens refreshed!", "Response");
                }
                else
                {
                    Log("Success! Access Tokens acquired!", "Response");
                }

                // This isn't really secure as the tokens will be stored in the application settings
                // but not protected - This code is there to help testing the sample, but you should consider
                // securing the Access Tokens in a better way, or force login each time the application starts.
                Properties.Settings.Default.oauth_token          = accessToken ["oauth_token"];
                Properties.Settings.Default.oauth_token_secret   = accessToken ["oauth_token_secret"];
                Properties.Settings.Default.oauth_session_handle = accessToken ["oauth_session_handle"];
                Properties.Settings.Default.x_oauth_user_name    = accessToken ["x_oauth_user_name"];
                Properties.Settings.Default.x_oauth_user_guid    = accessToken ["x_oauth_user_guid"];

                // The request returns other parameters that we do not use in this example.
                // They are listed here in comment in case you wanted to use them in your application.
                //double TokenExpire =double.Parse (accessToken ["oauth_expires_in"]) ;
                //double SessionExpire =double.Parse (accessToken ["oauth_authorization_expires_in"]) ;

                Properties.Settings.Default.Save();

                return(true);
            } catch (Exception ex) {
                LogError("Exception: " + ex.Message);
                return(false);
            }
        }