Beispiel #1
0
        //Final step. Take this authorization information and use it in the app
        public async Task<ActionResult> Callback()
        {
            RequestToken token = new RequestToken();
            token.Token = Request.Params["oauth_token"];
            token.Secret = Session["FitbitRequestTokenSecret"].ToString();
            token.Verifier = Request.Params["oauth_verifier"];

            string consumerKey = ConfigurationManager.AppSettings["FitbitConsumerKey"];
            string consumerSecret = ConfigurationManager.AppSettings["FitbitConsumerSecret"];

            //this is going to go back to Fitbit one last time (server to server) and get the user's permanent auth credentials

            //create the Authenticator object
            var authenticator = new Authenticator(consumerKey, consumerSecret);

            //execute the Authenticator request to Fitbit
            AuthCredential credential = await authenticator.ProcessApprovedAuthCallbackAsync(token);

            //here, we now have everything we need for the future to go back to Fitbit's API (STORE THESE):
            //  credential.AuthToken;
            //  credential.AuthTokenSecret;
            //  credential.UserId;

            // For demo, put this in the session managed by ASP.NET
            Session["FitbitAuthToken"] = credential.AuthToken;
            Session["FitbitAuthTokenSecret"] = credential.AuthTokenSecret;
            Session["FitbitUserId"] = credential.UserId;

            return RedirectToAction("Index", "Home");
        }
Beispiel #2
0
        public async Task <AuthCredential> ProcessApprovedAuthCallbackAsync(RequestToken token)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token", "RequestToken cannot be null");
            }

            if (string.IsNullOrWhiteSpace(token.Token))
            {
                throw new ArgumentNullException("token", "RequestToken.Token must not be null");
            }

            var oauthRequestToken = new AsyncOAuth.RequestToken(token.Token, token.Secret);
            var authorizer        = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
            var accessToken       = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, token.Verifier);

            var result = new AuthCredential
            {
                AuthToken       = accessToken.Token.Key,
                AuthTokenSecret = accessToken.Token.Secret,
                UserId          = accessToken.ExtraData["encoded_user_id"].FirstOrDefault()
            };

            return(result);
        }
		private void WhenProcessApprovedAuthCallback()
		{
            RequestToken token = new RequestToken();
            token.Token = "TAT";
            token.Verifier = "V";
			_credential = Authenticator().ProcessApprovedAuthCallback(token);
		}
Beispiel #4
0
        // note, these removed as part of a major breaking change refactor. 
        // Use GenerateAuthUrlFromRequestToken instead
        // more info: https://github.com/aarondcoleman/Fitbit.NET/wiki/Breaking-Change-on-1-24-2014-as-a-result-of-OAuth-update-in-Fitbit-API

        /*
		/// <summary>
		/// Use this method first to retrieve the url to redirect the user to to allow the url.
		/// Once they are done there, Fitbit will redirect them back to the predetermined completion URL
		/// </summary>
		/// <returns></returns>
		public string GetAuthUrlToken()
		{
			return GenerateAuthUrlToken(false);
		}

		public string GetAuthUrlTokenForcePromptingLogin()
		{
			return GenerateAuthUrlToken(true);
		}

        */
        public string GenerateAuthUrlFromRequestToken(RequestToken token, bool forceLogoutBeforeAuth)
		{
            RestRequest request = null;

			if(forceLogoutBeforeAuth)
				request = new RestRequest("oauth/logout_and_authorize"); //this url will force the user to type in username and password
			else
				request = new RestRequest("oauth/authorize");           //this url will show allow/deny if a user is currently logged in
			request.AddParameter("oauth_token", token.Token);
			var url = client.BuildUri(request).ToString();

			return url;
		} 
        public void Can_Retrieve_Access_Token_Authorization_Url()
        {
            RequestToken token = new RequestToken();
            token.Token = Configuration.TempAuthToken;
            //token.Secret = Configuration.TempAuthTokenSecret;
            token.Verifier = Configuration.TempAuthVerifier;

            string authUrl = authenticator.GenerateAuthUrlFromRequestToken(token, false);
            
            Assert.IsNotNull(authUrl);
            Console.Write("authUrl:" + authUrl);
            Assert.IsTrue(authUrl.Contains("https://api.fitbit.com/oauth/authorize?oauth_token="));
        }
Beispiel #6
0
 /// <summary>
 /// For Desktop authentication. Your code should direct the user to the FitBit website to get
 /// Their pin, they can then enter it here.
 /// </summary>
 /// <param name="pin"></param>
 /// <param name="token"></param>
 /// <returns></returns>
 public async Task<AuthCredential> GetAuthCredentialFromPinAsync(string pin, RequestToken token)
 {
     var oauthRequestToken = new AsyncOAuth.RequestToken(token.Token, token.Secret);
     var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
     var accessTokenResponse = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, pin);
     // save access token.
     var accessToken = accessTokenResponse.Token;
     return new AuthCredential
     {
         AuthToken = accessToken.Key,
         AuthTokenSecret = accessToken.Secret
     };
 }
Beispiel #7
0
        /// <summary>
        /// For Desktop authentication. Your code should direct the user to the FitBit website to get
        /// Their pin, they can then enter it here.
        /// </summary>
        /// <param name="pin"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task <AuthCredential> GetAuthCredentialFromPinAsync(string pin, RequestToken token)
        {
            var oauthRequestToken   = new AsyncOAuth.RequestToken(token.Token, token.Secret);
            var authorizer          = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
            var accessTokenResponse = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, pin);

            // save access token.
            var accessToken = accessTokenResponse.Token;

            return(new AuthCredential
            {
                AuthToken = accessToken.Key,
                AuthTokenSecret = accessToken.Secret
            });
        }
        public void Can_Retrieve_Access_Token_And_Access_Token_Secret()
        {
            RequestToken token = new RequestToken();
            token.Token = Configuration.TempAuthToken;
            //token.Secret = Configuration.TempAuthTokenSecret;
            token.Verifier = Configuration.TempAuthVerifier;


            AuthCredential authCredential = authenticator.ProcessApprovedAuthCallback(token);

            Assert.IsNotNull(authCredential.AuthToken);
            Console.WriteLine("AuthToken: " + authCredential.AuthToken);

            Assert.IsNotNull(authCredential.AuthTokenSecret);
            Console.WriteLine("AuthTokenSecret: " + authCredential.AuthTokenSecret);

            Assert.IsNotNull(authCredential.UserId); //encoded Fitbit UserId
            Console.WriteLine("Fitbit UserId: " + authCredential.UserId);
        }
Beispiel #9
0
        public async Task<AuthCredential> ProcessApprovedAuthCallbackAsync(RequestToken token)
        {
            if (token == null)
                throw new ArgumentNullException("token", "RequestToken cannot be null");

            if (string.IsNullOrWhiteSpace(token.Token))
                throw new ArgumentNullException("token", "RequestToken.Token must not be null");

            var oauthRequestToken = new AsyncOAuth.RequestToken(token.Token, token.Secret);
            var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
            var accessToken = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, token.Verifier);

            var result = new AuthCredential
            {
                AuthToken = accessToken.Token.Key,
                AuthTokenSecret = accessToken.Token.Secret,
                UserId = accessToken.ExtraData["encoded_user_id"].FirstOrDefault()
            };
            return result;
        }
Beispiel #10
0
        /// <summary>
        /// First step in the OAuth process is to ask Fitbit for a temporary request token. 
        /// From this you should store the RequestToken returned for later processing the auth token.
        /// </summary>
        /// <returns></returns>
        public RequestToken GetRequestToken()
        {
            client.Authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret);

            var request = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);

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

            RequestToken token = new RequestToken();

            token.Token = qs["oauth_token"];
            token.Secret = qs["oauth_token_secret"];

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new Exception("Request Token Step Failed");

            return token;
        }
Beispiel #11
0
		public AuthCredential ProcessApprovedAuthCallback(RequestToken token)
		{
            if (string.IsNullOrWhiteSpace(token.Token))
                throw new Exception("RequestToken.Token must not be null");
            //else if 

			client.Authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret);

			var request = new RestRequest("oauth/access_token", Method.POST);
			

			client.Authenticator = OAuth1Authenticator.ForAccessToken(
				this.ConsumerKey, this.ConsumerSecret, token.Token, token.Secret, token.Verifier
			);
			
			var response = client.Execute(request);

			//Assert.NotNull(response);
			//Assert.Equal(HttpStatusCode.OK, response.StatusCode);

			if (response.StatusCode != HttpStatusCode.OK)
				throw new FitbitException(response.Content, response.StatusCode);

			var qs = HttpUtility.ParseQueryString(response.Content); //not actually parsing querystring, but body is formatted like htat
			var oauth_token = qs["oauth_token"];
			var oauth_token_secret = qs["oauth_token_secret"];
			var encoded_user_id = qs["encoded_user_id"];
			//Assert.NotNull(oauth_token);
			//Assert.NotNull(oauth_token_secret);

			/*
			request = new RestRequest("account/verify_credentials.xml");
			client.Authenticator = OAuth1Authenticator.ForProtectedResource(
				this.ConsumerKey, this.ConsumerSecret, oauth_token, oauth_token_secret
			);

			response = client.Execute(request);

			 */

			return new AuthCredential()
			{
				AuthToken = oauth_token,
				AuthTokenSecret = oauth_token_secret,
				UserId = encoded_user_id
			};

			//Assert.NotNull(response);
			//Assert.Equal(HttpStatusCode.OK, response.StatusCode);

			//request = new RestRequest("statuses/update.json", Method.POST);
			//request.AddParameter("status", "Hello world! " + DateTime.Now.Ticks.ToString());
			//client.Authenticator = OAuth1Authenticator.ForProtectedResource(
			//    consumerKey, consumerSecret, oauth_token, oauth_token_secret
			//);

			//response = client.Execute(request);

			//Assert.NotNull(response);
			//Assert.Equal(HttpStatusCode.OK, response.StatusCode);
		}
Beispiel #12
0
		/// <summary>
		/// For Desktop authentication. Your code should direct the user to the FitBit website to get
		/// Their pin, they can then enter it here.
		/// </summary>
		/// <param name="pin"></param>
		/// <returns></returns>
		public AuthCredential GetAuthCredentialFromPin(string pin, RequestToken token)
		{
			var request = new RestRequest("oauth/access_token", Method.POST);
			client.Authenticator = OAuth1Authenticator.ForAccessToken(ConsumerKey, ConsumerSecret, token.Token, token.Secret, pin);
			
			var response = client.Execute(request);
			var qs = RestSharp.Contrib.HttpUtility.ParseQueryString(response.Content);

			return new AuthCredential()
			{
				AuthToken = qs["oauth_token"],
				AuthTokenSecret = qs["oauth_token_secret"],
				UserId = qs["encoded_user_id"]
			};
		}
Beispiel #13
0
        public string GenerateAuthUrlFromRequestToken(RequestToken token, bool forceLogoutBeforeAuth)
        {
            var url = Constants.BaseApiUrl + (forceLogoutBeforeAuth ? Constants.LogoutAndAuthorizeUri : Constants.AuthorizeUri);

            return(string.Format("{0}?oauth_token={1}", url, token.Token));
        }
Beispiel #14
0
 public string GenerateAuthUrlFromRequestToken(RequestToken token, bool forceLogoutBeforeAuth)
 {
     var url = Constants.BaseApiUrl + (forceLogoutBeforeAuth ? Constants.LogoutAndAuthorizeUri : Constants.AuthorizeUri);
     return string.Format("{0}?oauth_token={1}", url, token.Token);
 }