예제 #1
0
		public bool TryGetAccessToken(string verificationCode, out GoogleOAuthException error)
		{
			error = null;
			try
			{
				GetAccessToken(verificationCode);
				return true;
			}
			catch (GoogleOAuthException ex)
			{
				error = ex;
				return false;
			}
		}
예제 #2
0
		public bool GetAccessToken(string verificationCode)
		{
			var p = new NameValueCollection();
			p.Add("client_id", this.ClientId);
			p.Add("client_secret", this.ClientSecret);
			p.Add("code", verificationCode);
			p.Add("redirect_uri", string.IsNullOrEmpty(this.RedirectUrl) ? OobRedirectUrl : this.RedirectUrl);
			p.Add("grant_type", "authorization_code");

			var url = Util.BuildUrl(OobRedirectUrl, p);
			var data = Util.DownloadUrl(url);

			if (!parseToken(data))
			{
				var ex = new GoogleOAuthException("Failed to get Access Token.  Check ServerResponse for Details.");
				ex.ServerResponse = data;
				throw ex;
			}

			return true;
		}
예제 #3
0
		public bool TryRefreshAccessToken(out GoogleOAuthException error)
		{
			error = null;
			try 
			{ 
				RefreshAccessToken();
				return true;
			}
			catch (GoogleOAuthException ex)
			{
				error = ex;
				return false;
			}
		}
예제 #4
0
		public bool GetAccessToken(string verificationCode)
		{
			if (string.IsNullOrEmpty(verificationCode))
				throw new GoogleOAuthException("Missing Verification Code!");

			//Again make sure these are in alpha order
			var p = new NameValueCollection();
			p.Add("oauth_consumer_key", this.ConsumerKey);
			p.Add("oauth_nonce", Util.RandomInt64().ToString());
			p.Add("oauth_signature_method", "HMAC-SHA1");
			p.Add("oauth_timestamp", Util.EpochNow().ToString());
			p.Add("oauth_token", this.Token);
			p.Add("oauth_verifier", verificationCode);
			p.Add("oauth_version", "1.0");

			//Generating the signature, this time we have a TokenSecret we must include
			p.Add("oauth_signature", Util.GenerateSignature(OAuthGetAccessTokenUrl, p, this.ConsumerSecret, this.TokenSecret));

			//Get the response
			var url = Util.BuildUrl(OAuthGetAccessTokenUrl, p);
			var data = Util.DownloadUrl(url);
			var responseParameters = Util.ParseQueryString(data);

			//Parse out the tokens in the response
			this.Token = responseParameters["oauth_token"] ?? "";
			this.TokenSecret = responseParameters["oauth_token_secret"] ?? "";

			//If we have no tokens, we had an issue
			if (string.IsNullOrEmpty(this.Token) || string.IsNullOrEmpty(this.TokenSecret))
			{
				var ex = new GoogleOAuthException("Missing Token or TokenSecret in response.  Check ServerResponse.");
				ex.ServerResponse = data;
				throw ex;
			}

			//Everything went ok!
			return true;
		}
예제 #5
0
		/// <summary>
		/// Authorizes an account with OAuth for the specified Google scopes and gets the URL to display to the user for further authorization.
		/// You should call GetAccessToken() next with the verification code returned after the user Grants your application access.
		/// </summary>
		/// <returns>Returns the Authorization URL to display for the user.</returns>
		public string GetAuthUrl()
		{
			//Step 1: Get Request Token
			// IMPORTANT NOTE: For the GenerateSignature to work properly all the parameters in this
			//  collection must be in alpha order!!!
			var p = new NameValueCollection();
			p.Add("oauth_callback", this.CallbackUrl);
			p.Add("oauth_consumer_key", this.ConsumerKey);
			p.Add("oauth_nonce", Util.RandomInt64().ToString());
			p.Add("oauth_signature_method", "HMAC-SHA1");
			p.Add("oauth_timestamp", Util.EpochNow().ToString());
			p.Add("oauth_version", "1.0");
			p.Add("scope", string.Join(" ", Scopes));
			p.Add("xoauth_displayname", DisplayName);

			//Add the last paramaeter which uses the existing ones to generate a signature
			p.Add("oauth_signature", Util.GenerateSignature(OAuthGetRequestTokenUrl, p, this.ConsumerSecret, null));

			//Build the url and download the data
			var url = Util.BuildUrl(OAuthGetRequestTokenUrl, p);
			var data = Util.DownloadUrl(url);
			var responseParameters = Util.ParseQueryString(data);

			//Parse out the tokens in the response
			this.Token = responseParameters["oauth_token"] ?? "";
			this.TokenSecret = responseParameters["oauth_token_secret"] ?? "";

			//If the tokens aren't there, we had an issue
			if (string.IsNullOrEmpty(this.Token) || string.IsNullOrEmpty(this.TokenSecret))
			{
				var ex = new GoogleOAuthException("Missing Token or TokenSecret in response.  Check ServerResponse.");
				ex.ServerResponse = data;
				throw ex;
			}

			//Build the url to show the user
			url = string.Format("{0}?oauth_token={1}", OAuthAuthorizeTokenUrl, this.Token);

			//Mobile support can be forced
			if (Mobile)
				url += "&btmpl=mobile";

			return url;
		}
예제 #6
0
		public bool TryGetAuthUrl(out string authUrl, out GoogleOAuthException error)
		{
			authUrl = string.Empty;
			error = null;
			try
			{
				authUrl = GetAuthUrl();
				return true;
			}
			catch (GoogleOAuthException ex)
			{
				error = ex;
				return false;
			}
		}
예제 #7
0
		/// <summary>
		/// Validates the given token and tokenSecret to ensure it is still valid for the given scopes
		/// </summary>
		/// <param name="token">Access Token returned from Authorization</param>
		/// <param name="tokenSecret">Access Token Secret returned from Authorization</param>
		/// <returns>True if the Token is still valid and is valid for the given scopes</returns>
		public bool ValidateTokens(string token, string tokenSecret)
		{
			//This is largely unadvertised as a means to validate OAuth Token and token scope.
			// This is the documented way to get AuthSub info, but it works for OAuth too!

			//Important that these parameters are in alpha order
			var p = new NameValueCollection();
			p.Add("oauth_consumer_key", this.ConsumerKey);
			p.Add("oauth_nonce", Util.RandomInt64().ToString());
			p.Add("oauth_signature_method", "HMAC-SHA1");
			p.Add("oauth_timestamp", Util.EpochNow().ToString());
			p.Add("oauth_token", token);
			p.Add("oauth_version", "1.0");

			//Build the signature
			p.Add("oauth_signature", Util.GenerateSignature(OAuthVerifyTokensUrl, p, this.ConsumerSecret, tokenSecret));

			//Get a response
			var url = Util.BuildUrl(OAuthVerifyTokensUrl, p);
			var data = Util.DownloadUrl(url);

			//The respone from google comes in lines
			var lines = data.Split('\n');

			//No lines parsed? had an issue
			if (lines == null || lines.Length <= 0)
				throw new GoogleOAuthException("Empty Response from Validation Call");
			
			//We want to find all the valid scopes returned 
			// eg format:  Scope=...\nScope2=... etc.
			var validScopes = new List<string>();
			//There will be a line Secure=true if the token is valid still
			bool secure = false;

			//Parse out the lines
			foreach (var line in lines)
			{
				if (line.StartsWith("Scope", StringComparison.InvariantCultureIgnoreCase)
					&& line.Contains('='))
				{
					var scope = line.Substring(line.IndexOf('=') + 1);

					if (!string.IsNullOrEmpty(scope))
						validScopes.Add(scope);
				}
				else if (line.StartsWith("Secure=true", StringComparison.InvariantCultureIgnoreCase))
					secure = true;
			}

			//Find if any required scopes are missing from the valid scopes
			var missingScopes = from s in this.Scopes
								where !validScopes.Exists(vs => vs.Equals(s, StringComparison.InvariantCultureIgnoreCase))
								select s;

			if (missingScopes.Count() > 0)
			{
				var ex = new GoogleOAuthException("Access Token is not valid for one or more requested scopes");
				ex.Data.Add("MissingScopes", missingScopes.ToArray());
				throw ex;
			}

			if (!secure)
				throw new GoogleOAuthException("Validation: Account not Secured");

			return true;
		}
예제 #8
0
		public bool TryValidateTokens(string token, string tokenSecret, out GoogleOAuthException error)
		{
			error = null;

			try
			{
				return ValidateTokens(token, tokenSecret);
			}
			catch (GoogleOAuthException ex)
			{
				error = ex;
				return false;
			}
		}