Ejemplo n.º 1
0
 protected override Uri GetServiceLoginUrl(Uri returnUrl) {
     var builder = new UriBuilder(Endpoints.Authorization);
     builder.AppendQueryArgument("response_type", "code");
     builder.AppendQueryArgument("client_id", ClientId);
     builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
     return builder.Uri;
 }
Ejemplo n.º 2
0
        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            var builder = new UriBuilder(TokenEndpoint);
            builder.AppendQueryArgument("client_id", this.appId);
            builder.AppendQueryArgument("client_secret", this.clientSecret);
            builder.AppendQueryArgument("code", authorizationCode);
            var redirectUri = NormalizeHexEncoding(returnUrl.AbsoluteUri);
            builder.AppendQueryArgument("redirect_uri", redirectUri);

            //builder.AppendQueryArgument("grant_type", "client_credentials");

            using (WebClient client = new WebClient())
            {
                string data = client.DownloadString(builder.Uri);
                if (string.IsNullOrEmpty(data))
                {
                    return null;
                }

                JObject dataObject = JObject.Parse(data);

                //TODO: Проверять успешность запроса
                var accessToken = dataObject["access_token"].ToString();
                var userId = (int)dataObject["user_id"];

                HttpContext.Current.Session[accessToken] = Convert.ToString(userId);
                return accessToken;
            }
        }
Ejemplo n.º 3
0
        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            var url = ApiEndpoint + "users.get";
            var builder = new UriBuilder(url);
            builder.AppendQueryArgument("access_token", accessToken);
            var userId = Convert.ToString(HttpContext.Current.Session[accessToken]);
            if (!string.IsNullOrWhiteSpace(userId))
            {
                builder.AppendQueryArgument("uids", userId);
            }
            using (WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                string data = client.DownloadString(builder.Uri);
                if (string.IsNullOrEmpty(data))
                {
                    return null;
                }

                dynamic jsonResult = JObject.Parse(data);

                //TODO: Проверять успешность запроса
                var userData = new Dictionary<string, string>();
                userData.Add("id", Convert.ToString(jsonResult.response[0].uid));
                userData.Add("username", Convert.ToString(jsonResult.response[0].uid));
                userData.Add("name", string.Format("{0} {1}",
                    Convert.ToString(jsonResult.response[0].first_name),
                    Convert.ToString(jsonResult.response[0].last_name)));
                return userData;
            }
        }
        /// <summary>
        /// Gets the full url pointing to the login page for this client. The url should include the specified return url so that when the login completes, user is redirected back to that url.
        /// </summary>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns>
        /// An absolute URL.
        /// </returns>
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            var uriBuilder = new UriBuilder(AuthorizeUrl);
            uriBuilder.AppendQueryArgument("client_id", this.clientId);
            uriBuilder.AppendQueryArgument("redirect_uri", returnUrl.ToString());

            return uriBuilder.Uri;
        }
        /// <summary>
        /// The get service login url.
        /// </summary>
        /// <param name="returnUrl">
        /// The return url.
        /// </param>
        /// <returns>An absolute URI.</returns>
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            var builder = new UriBuilder(_authorizationEndpoint);

            builder.AppendQueryArgument("client_id", _appId);
            builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);

            return builder.Uri;
        }
Ejemplo n.º 6
0
 protected override Uri GetServiceLoginUrl(Uri returnUrl)
 {
     var builder = new UriBuilder(AuthorizationEndpoint);
     builder.AppendQueryArgument("client_id", this.appId);
     builder.AppendQueryArgument("scope", "groups, wall");
     builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
     builder.AppendQueryArgument("display", "page");
     return builder.Uri;
 }
        internal Uri GetServiceLoginUrlInternal(Uri returnUrl)
        {
            UriBuilder uriBuilder = new UriBuilder(AuthorizationEndpoint);
            uriBuilder.AppendQueryArgument("client_id", _clientID);
            uriBuilder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
            //uriBuilder.AppendQueryArgument("scope", "user");

            return uriBuilder.Uri;
        }
Ejemplo n.º 8
0
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            var builder = new UriBuilder(AUTHORIZATION_ENDPOINT);

            builder.AppendQueryArgument("client_id", _appId);
            builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
            builder.AppendQueryArgument("scope", "user:email");

            return builder.Uri;
        }
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            UriBuilder uriBuilder = new UriBuilder(AuthorizationEndpoint);
            uriBuilder.AppendQueryArgument("client_id", this.clientId);
            uriBuilder.AppendQueryArgument("redirect_uri", returnUrl.GetLeftPart(UriPartial.Path));
            uriBuilder.AppendQueryArgument("response_type", "code");
            uriBuilder.AppendQueryArgument("scope", "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email");
            uriBuilder.AppendQueryArgument("state", returnUrl.Query.Substring(1));

            return uriBuilder.Uri;
        }
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            UriBuilder builder = new UriBuilder(AuthorizationEndpoint);
            builder.AppendQueryArgument("client_id", ApplicationId);
            builder.AppendQueryArgument("response_type", "code");
            builder.AppendQueryArgument("scope", Scope);
            builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
            builder.AppendQueryArgument("nonce", Guid.NewGuid().ToString().Replace("-", ""));

            return builder.Uri;
        }
        /// <summary>
        /// The get service login url.
        /// </summary>
        /// <param name="returnUrl">
        /// The return url.
        /// </param>
        /// <returns>An absolute URI.</returns>
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            // Note: Facebook doesn't like us to url-encode the redirect_uri value
            var builder = new UriBuilder(AuthorizationEndpoint);

            builder.AppendQueryArgument("client_id",this.appId);
            builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
            builder.AppendQueryArgument("scope", this.scope);
            builder.AppendQueryArgument("response_type", "code");

            return builder.Uri;
        }
Ejemplo n.º 12
0
        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            UriBuilder uriBuilder = new UriBuilder(UserInfoEndpoint);
            uriBuilder.AppendQueryArgument("access_token", accessToken);

            WebRequest webRequest = WebRequest.Create(uriBuilder.Uri);
            using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
            {
                if (webResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (var responseStream = webResponse.GetResponseStream())
                    {
                        if (responseStream == null)
                            return null;

                        StreamReader streamReader = new StreamReader(responseStream);

                        Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(streamReader.ReadToEnd());

                        // Add a username field in the dictionary
                        if (values.ContainsKey("email") && !values.ContainsKey("username"))
                            values.Add("username", values["email"]);

                        return values;
                    }
                }
            }

            return null;
        }
        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            var client = new RestClient();

            var builder = new UriBuilder(UsersEndpoint);

            builder.AppendQueryArgument("access_token", accessToken);

            var request = new RestRequest(builder.Uri.AbsoluteUri, Method.GET);

            var response = client.Execute(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
                return new Dictionary<string, string>();

            var json = JObject.Parse(response.Content);

            var strs = new Dictionary<string, string>();

            strs["id"] = json["id"].ToString();
            strs["username"] = json["login"].ToString();

            try
            {
                strs["name"] = json["name"].ToString();
            }
            catch
            {
            }

            return strs;
        }
Ejemplo n.º 14
0
		public ActionResult Authorize() {
			var incomingAuthzRequest = this.authorizationServer.ReadAuthorizationRequest(this.Request);
			if (incomingAuthzRequest == null) {
				return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Missing authorization request");
			}

			var returnTo = new UriBuilder(this.Url.AbsoluteAction("AuthorizeWithMicrosoftAccount"));
			returnTo.AppendQueryArgument("nestedAuth", this.Request.Url.Query);
			var scopes = new[] { "wl.signin", "wl.basic", "wl.emails" }; // this is a subset of what the client app asks for, ensuring automatic approval.
			return LiveConnectClient.PrepareRequestUserAuthorization(scopes, returnTo.Uri).AsActionResult();
		}
        /// <summary>
        /// Given the access token, gets the logged-in user's data. The returned dictionary must include two keys 'id', and 'username'.
        /// </summary>
        /// <param name="accessToken">The access token of the current user.</param>
        /// <returns>
        /// A dictionary contains key-value pairs of user data
        /// </returns>
        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            using (var webClient = CreateWebClient())
            {
                var uriBuilder = new UriBuilder(ProfileUrl);
                uriBuilder.AppendQueryArgument("access_token", accessToken);

                var profileResponse = webClient.DownloadString(uriBuilder.Uri);
                var profile = JsonConvert.DeserializeObject<dynamic>(profileResponse);

                return new Dictionary<string, string>
                       {
                           { "login", profile.login.ToString() },
                           { "id", profile.id.ToString() },
                           { "avatar_url", profile.avatar_url.ToString() },
                           { "gravatar_id", profile.gravatar_id.ToString() },
                           { "url", profile.url.ToString() },
                           { "name", profile.name.ToString() },
                           { "company", profile.company.ToString() },
                           { "blog", profile.blog.ToString() },
                           { "location", profile.location.ToString() },
                           { "email", profile.email.ToString() },
                           { "hireable", profile.hireable.ToString() },
                           { "bio", profile.bio.ToString() },
                           { "public_repos", profile.public_repos.ToString() },
                           { "public_gists", profile.public_gists.ToString() },
                           { "followers", profile.followers.ToString() },
                           { "following", profile.following.ToString() },
                           { "html_url", profile.html_url.ToString() },
                           { "created_at", profile.created_at.ToString() },
                           { "type", profile.type.ToString() },
                           { "total_private_repos", profile.total_private_repos.ToString() },
                           { "owned_private_repos", profile.owned_private_repos.ToString() },
                           { "private_gists", profile.private_gists.ToString() },
                           { "disk_usage", profile.disk_usage.ToString() },
                           { "collaborators", profile.collaborators.ToString() },
                           { "plan_name", profile.plan.name.ToString() },
                           { "plan_space", profile.plan.space.ToString() },
                           { "plan_collaborators", profile.plan.collaborators.ToString() },
                           { "plan_private_repos", profile.plan.private_repos.ToString() }
                       };
            }
        }
        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            UriBuilder builder = new UriBuilder(ResourceEndpoint);
            builder.AppendQueryArgument("schema", Scope);

            var request = WebRequest.Create(builder.ToString());
            request.Headers["Authorization"] = string.Concat("Bearer ", accessToken);

            OpenIdConnectGraph data;
            using (WebResponse response = request.GetResponse())
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                data = JsonConvert.DeserializeObject<OpenIdConnectGraph>(reader.ReadToEnd());
            }

            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.AddItemIfNotEmpty("fullname", data.Name);
            dictionary.AddItemIfNotEmpty("id", data.Email);
            dictionary.AddItemIfNotEmpty("email", data.Email);
            dictionary.AddItemIfNotEmpty("firstname", data.Firstname);
            dictionary.AddItemIfNotEmpty("lastname", data.Lastname);
            return dictionary;
        }
Ejemplo n.º 17
0
 protected override Uri GetServiceLoginUrl(Uri returnUrl)
 {
     var uriBuilder = new UriBuilder(AuthorizationEndpoint);
     var dict = new Dictionary<string, string>{
         {
             "client_id",
             this.appId
         },
         {
             "redirect_uri",
             returnUrl.AbsoluteUri
         },
         {
             "response_type",
             "code"
         }
     };
     foreach (var item in dict)
     {
         uriBuilder.AppendQueryArgument(item.Key, item.Value);
     }
     return uriBuilder.Uri;
 }
        /// <summary>
        /// Obtains an access token given an authorization code and callback URL.
        /// </summary>
        /// <param name="returnUrl">
        /// The return url.
        /// </param>
        /// <param name="authorizationCode">
        /// The authorization code.
        /// </param>
        /// <returns>
        /// The access token.
        /// </returns>
        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            // Note: Facebook doesn't like us to url-encode the redirect_uri value
            var builder = new UriBuilder(TokenEndpoint);
            builder.AppendQueryArgument("client_id", this.appId );
            builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri );
            builder.AppendQueryArgument("client_secret", this.appSecret);
            builder.AppendQueryArgument("code", authorizationCode);

            using (WebClient client = new WebClient())
            {
                string data = client.DownloadString(builder.Uri);
                if (string.IsNullOrEmpty(data))
                {
                    return null;
                }
                var parsedQueryString = System.Web.Helpers.Json.Decode(data);

                if (parsedQueryString["error"] != null)
                {
                    return null;
                }

                this.UserId = parsedQueryString["user_id"];

                return parsedQueryString["access_token"];
            }
        }
        public bool AuthorizeExternal(ref IAuthorizationState authorization, string refreshToken, string AuthorizationCode)
        {
            if ((authorization == null))
            {
                authorization = new AuthorizationState
                {
                    Callback = _redirectUri,
                    RefreshToken = refreshToken
                };
            }

            bool refreshFailed = false;
            if (AccessTokenHasToBeRefreshed(authorization))
            {
                try
                {
                    refreshFailed = !RefreshAuthorization(authorization);
                }
                catch (ProtocolException)
                {
                    //The refreshtoken is not valid anymore
                }
            }

            if (authorization.AccessToken == null || refreshFailed)
            {
                if (string.IsNullOrEmpty(AuthorizationCode))
                {
                    var uri = GetAuthorizationUri(authorization);
                    int retval = ShellExecute(IntPtr.Zero, "open", uri.ToString(), "", "", ShowCommands.SW_NORMAL).ToInt32();
                    return retval > 32;
                }
                else
                {
                    var uri = new UriBuilder(_redirectUri);
                    uri.AppendQueryArgument("code", AuthorizationCode);
                    ProcessUserAuthorization(uri.Uri, authorization);
                }
            }
            return !refreshFailed;
        }
Ejemplo n.º 20
0
        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            var builder = new UriBuilder(TOKEN_ENDPOINT);

            builder.AppendQueryArgument("client_id", _appId);
            builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
            builder.AppendQueryArgument("client_secret", _appSecret);
            builder.AppendQueryArgument("code", authorizationCode);

            using (var client = new WebClient()) {
                string data = client.DownloadString(builder.Uri);

                if (string.IsNullOrEmpty(data))
                    return null;

                NameValueCollection parsedQueryString = HttpUtility.ParseQueryString(data);
                return parsedQueryString["access_token"];
            }
        }
Ejemplo n.º 21
0
		/// <summary>
		/// Obtains an access token after a successful user authorization.
		/// </summary>
		/// <param name="verifier">The verifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// The access token assigned by the Service Provider.
		/// </returns>
		public async Task<AccessTokenResponse> ProcessUserAuthorizationAsync(string verifier, CancellationToken cancellationToken = default(CancellationToken)) {
			Requires.NotNull(verifier, "verifier");
			Verify.Operation(this.ConsumerKey != null, Strings.RequiredPropertyNotYetPreset, "ConsumerKey");
			Verify.Operation(this.TemporaryCredentialStorage != null, Strings.RequiredPropertyNotYetPreset, "TemporaryCredentialStorage");
			Verify.Operation(this.ServiceProvider != null, Strings.RequiredPropertyNotYetPreset, "ServiceProvider");

			var temporaryCredential = this.TemporaryCredentialStorage.RetrieveTemporaryCredential();

			using (var client = this.CreateHttpClient(new AccessToken(temporaryCredential.Key, temporaryCredential.Value))) {
				var requestUri = new UriBuilder(this.ServiceProvider.TokenRequestEndpoint);
				requestUri.AppendQueryArgument(Protocol.VerifierParameter, verifier);
				var request = new HttpRequestMessage(this.ServiceProvider.TokenRequestEndpointMethod, requestUri.Uri);
				using (var response = await client.SendAsync(request, cancellationToken)) {
					response.EnsureSuccessStatusCode();

					// Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec.
					string content = await response.Content.ReadAsStringAsync();
					var responseData = HttpUtility.ParseQueryString(content);
					string accessToken = responseData[Protocol.TokenParameter];
					string tokenSecret = responseData[Protocol.TokenSecretParameter];
					ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(accessToken), MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenParameter);
					ErrorUtilities.VerifyProtocol(tokenSecret != null, MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenSecretParameter);

					responseData.Remove(Protocol.TokenParameter);
					responseData.Remove(Protocol.TokenSecretParameter);
					return new AccessTokenResponse(accessToken, tokenSecret, responseData);
				}
			}
		}
Ejemplo n.º 22
0
        /// <summary>
        /// Queries the access token from the specified authorization code.
        /// </summary>
        /// <returns>The access token.</returns>
        /// <param name="returnUrl">Return URL.</param>
        /// <param name="authorizationCode">Authorization code.</param>
        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            var builder = new UriBuilder(tokenEndpoint);

            builder.AppendQueryArgument("client_id", this.appId);
            builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
            builder.AppendQueryArgument("client_secret", this.appSecret);
            builder.AppendQueryArgument("code", authorizationCode);

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                var data = client.DownloadString(builder.Uri);
                if (string.IsNullOrEmpty(data))
                    return null;

                var parsedQueryString = HttpUtility.ParseQueryString(data);
                return parsedQueryString["access_token"];
            }
        }
		/// <summary>
		/// Prepares an OAuth message that begins an authorization request that will
		/// redirect the user to the VitaDock website to provide that authorization.
		/// </summary>
		/// <param name="callback">The absolute URI that the Service Provider should redirect the
		/// User Agent to upon successful authorization, or <c>null</c> to signify an out of band return.</param>
		/// <param name="requestParameters">Extra parameters to add to the request token message.  Optional.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// The URL to direct the user agent to for user authorization.
		/// </returns>
		public async new Task<Uri> RequestUserAuthorizationAsync(Uri callback = null, IEnumerable<KeyValuePair<string, string>> requestParameters = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			// Requires.NotNull(callback, "callback"); - VitaDock API does not work if this is present
			Verify.Operation(this.ConsumerKey != null, "ConsumerKey is not preset", "ConsumerKey");
			Verify.Operation(this.TemporaryCredentialStorage != null, "TemporaryCredentialStorage is not preset", "TemporaryCredentialStorage");
			Verify.Operation(this.ServiceProvider != null, "ServiceProvider is not preset", "ServiceProvider");

			// Obtain temporary credentials before the redirect.
			using (var client = this.CreateHttpClient(new AccessToken()))
			{
				var requestUri = new UriBuilder(this.ServiceProvider.TemporaryCredentialsRequestEndpoint);

				// VitaDock specifies that callback paramter must not be sent
				OauthHelperUtility.AppendQueryArgs(requestUri, requestParameters);
				var request = new HttpRequestMessage(this.ServiceProvider.TemporaryCredentialsRequestEndpointMethod, requestUri.Uri);
				using (var response = await client.SendAsync(request, cancellationToken))
				{
					response.EnsureSuccessStatusCode();
					cancellationToken.ThrowIfCancellationRequested();

					// Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec.
					string content = await response.Content.ReadAsStringAsync();
					var responseData = HttpUtility.ParseQueryString(content);
					string identifier = responseData["oauth_token"];
					string secret = responseData["oauth_token_secret"];
					Validation.Requires.That(!string.IsNullOrEmpty(identifier), "oauth_token_secret", "Token was missing in message");
					Validation.Requires.That(!string.IsNullOrEmpty(secret), "oauth_token_secret", "Token was missing in message");

					// Save the temporary credential we received so that after user authorization
					// we can use it to obtain the access token.
					cancellationToken.ThrowIfCancellationRequested();
					this.TemporaryCredentialStorage.SaveTemporaryCredential(identifier, secret);

					// Construct the user authorization URL so our caller can direct a browser to it.
					var authorizationEndpoint = new UriBuilder(this.ServiceProvider.ResourceOwnerAuthorizationEndpoint);
					authorizationEndpoint.AppendQueryArgument("oauth_token", identifier);
					return authorizationEndpoint.Uri;
				}
			}
		}
Ejemplo n.º 24
0
        /// <summary>
        /// Queries the access token from the specified authorization code to complete the OAuth2 dance.
        /// </summary>
        /// <param name="returnUrl">
        /// The return URL. 
        /// </param>
        /// <param name="authorizationCode">
        /// The authorization code. 
        /// </param>
        /// <returns>
        /// The query access token.
        /// </returns>
        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            var b = new UriBuilder(TokenEndpoint);
            b.AppendQueryArgument("client_id", _appId);
            b.AppendQueryArgument("client_secret", _appSecret);
            b.AppendQueryArgument("code", authorizationCode);

            var tokenRequest = WebRequest.Create(b.ToString());
            var tokenResponse = (HttpWebResponse)tokenRequest.GetResponse();
            if (tokenResponse.StatusCode == HttpStatusCode.OK)
            {
                using (var responseStream = tokenResponse.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        var reader = new StreamReader(responseStream);
                        var responseJson = reader.ReadToEnd();
                        var deserializedProduct = JsonConvert.DeserializeObject<YammerToken>(responseJson);

                        Debug.WriteLine("QueryAccessToken() returned {0}", deserializedProduct.access_token.token);

                        return deserializedProduct.access_token.token;
                    }
                }
            }

            Debug.WriteLine("QueryAccessToken() returned null");
            return null;
        }
Ejemplo n.º 25
0
		/// <summary>
		/// Obtains an access token for a new account at the Service Provider via 2-legged OAuth.
		/// </summary>
		/// <param name="requestParameters">Any applicable parameters to include in the query string of the token request.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>The access token.</returns>
		public async Task<AccessTokenResponse> RequestNewClientAccountAsync(IEnumerable<KeyValuePair<string, string>> requestParameters = null, CancellationToken cancellationToken = default(CancellationToken)) {
			Verify.Operation(this.ConsumerKey != null, Strings.RequiredPropertyNotYetPreset, "ConsumerKey");
			Verify.Operation(this.ServiceProvider != null, Strings.RequiredPropertyNotYetPreset, "ServiceProvider");

			using (var handler = this.CreateMessageHandler()) {
				using (var client = this.CreateHttpClient(handler)) {
					string identifier, secret;

					var requestUri = new UriBuilder(this.ServiceProvider.TemporaryCredentialsRequestEndpoint);
					requestUri.AppendQueryArgument(Protocol.CallbackParameter, "oob");
					requestUri.AppendQueryArgs(requestParameters);
					var request = new HttpRequestMessage(this.ServiceProvider.TemporaryCredentialsRequestEndpointMethod, requestUri.Uri);
					using (var response = await client.SendAsync(request, cancellationToken)) {
						response.EnsureSuccessStatusCode();
						cancellationToken.ThrowIfCancellationRequested();

						// Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec.
						string content = await response.Content.ReadAsStringAsync();
						var responseData = HttpUtility.ParseQueryString(content);
						identifier = responseData[Protocol.TokenParameter];
						secret = responseData[Protocol.TokenSecretParameter];
						ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(identifier), MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.TokenParameter);
						ErrorUtilities.VerifyProtocol(secret != null, MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.TokenSecretParameter);
					}

					// Immediately exchange the temporary credential for an access token.
					handler.AccessToken = identifier;
					handler.AccessTokenSecret = secret;
					request = new HttpRequestMessage(this.ServiceProvider.TokenRequestEndpointMethod, this.ServiceProvider.TokenRequestEndpoint);
					using (var response = await client.SendAsync(request, cancellationToken)) {
						response.EnsureSuccessStatusCode();

						// Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec.
						string content = await response.Content.ReadAsStringAsync();
						var responseData = HttpUtility.ParseQueryString(content);
						string accessToken = responseData[Protocol.TokenParameter];
						string tokenSecret = responseData[Protocol.TokenSecretParameter];
						ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(accessToken), MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenParameter);
						ErrorUtilities.VerifyProtocol(tokenSecret != null, MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenSecretParameter);

						responseData.Remove(Protocol.TokenParameter);
						responseData.Remove(Protocol.TokenSecretParameter);
						return new AccessTokenResponse(accessToken, tokenSecret, responseData);
					}
				}
			}
		}
        /// <summary>
        /// The get user data.
        /// </summary>
        /// <param name="accessToken">
        /// The access token.
        /// </param>
        /// <returns>A dictionary of profile data.</returns>
        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            var uriBuilder = new UriBuilder(_userEndpoint);
            uriBuilder.AppendQueryArgument("access_token", accessToken);

            using (var webClient = new WebClient())
            {
                webClient.Headers.Add(HttpRequestHeader.UserAgent, "DDD East Anglia (www.dddeastanglia.com) .NET 4.0 WebClient");

                using (var responseStream = webClient.OpenRead(uriBuilder.Uri))
                using (var streamReader = new StreamReader(responseStream))
                {
                    return Json.Decode<Dictionary<string, string>>(streamReader.ReadToEnd());
                }
            }
        }
Ejemplo n.º 27
0
		/// <summary>
		/// Prepares an OAuth message that begins an authorization request that will
		/// redirect the user to the Service Provider to provide that authorization.
		/// </summary>
		/// <param name="callback">The absolute URI that the Service Provider should redirect the
		/// User Agent to upon successful authorization, or <c>null</c> to signify an out of band return.</param>
		/// <param name="requestParameters">Extra parameters to add to the request token message.  Optional.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// The URL to direct the user agent to for user authorization.
		/// </returns>
		public async Task<Uri> RequestUserAuthorizationAsync(Uri callback = null, IEnumerable<KeyValuePair<string, string>> requestParameters = null, CancellationToken cancellationToken = default(CancellationToken)) {
			Requires.NotNull(callback, "callback");
			Verify.Operation(this.ConsumerKey != null, Strings.RequiredPropertyNotYetPreset, "ConsumerKey");
			Verify.Operation(this.TemporaryCredentialStorage != null, Strings.RequiredPropertyNotYetPreset, "TemporaryCredentialStorage");
			Verify.Operation(this.ServiceProvider != null, Strings.RequiredPropertyNotYetPreset, "ServiceProvider");

			// Obtain temporary credentials before the redirect.
			using (var client = this.CreateHttpClient(new AccessToken())) {
				var requestUri = new UriBuilder(this.ServiceProvider.TemporaryCredentialsRequestEndpoint);
				requestUri.AppendQueryArgument(Protocol.CallbackParameter, callback != null ? callback.AbsoluteUri : "oob");
				requestUri.AppendQueryArgs(requestParameters);
				var request = new HttpRequestMessage(this.ServiceProvider.TemporaryCredentialsRequestEndpointMethod, requestUri.Uri);
				using (var response = await client.SendAsync(request, cancellationToken)) {
					response.EnsureSuccessStatusCode();
					cancellationToken.ThrowIfCancellationRequested();

					// Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec.
					string content = await response.Content.ReadAsStringAsync();
					var responseData = HttpUtility.ParseQueryString(content);
					ErrorUtilities.VerifyProtocol(string.Equals(responseData[Protocol.CallbackConfirmedParameter], "true", StringComparison.Ordinal), MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.CallbackConfirmedParameter);
					string identifier = responseData[Protocol.TokenParameter];
					string secret = responseData[Protocol.TokenSecretParameter];
					ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(identifier), MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.TokenParameter);
					ErrorUtilities.VerifyProtocol(secret != null, MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.TokenSecretParameter);

					// Save the temporary credential we received so that after user authorization
					// we can use it to obtain the access token.
					cancellationToken.ThrowIfCancellationRequested();
					this.TemporaryCredentialStorage.SaveTemporaryCredential(identifier, secret);

					// Construct the user authorization URL so our caller can direct a browser to it.
					var authorizationEndpoint = new UriBuilder(this.ServiceProvider.ResourceOwnerAuthorizationEndpoint);
					authorizationEndpoint.AppendQueryArgument(Protocol.TokenParameter, identifier);
					return authorizationEndpoint.Uri;
				}
			}
		}
Ejemplo n.º 28
0
        /// <summary>
        /// Given the access token, gets the logged-in user's data. The returned dictionary must include two keys 'id', and 'username'.
        /// </summary>
        /// <param name="accessToken">
        /// The access token of the current user. 
        /// </param>
        /// <returns>
        /// A dictionary contains key-value pairs of user data 
        /// </returns>
        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            var b = new UriBuilder(CurrentUserEndpoint);
            b.AppendQueryArgument("access_token", accessToken);

            var tokenRequest = WebRequest.Create(b.ToString());
            var tokenResponse = (HttpWebResponse)tokenRequest.GetResponse();
            if (tokenResponse.StatusCode == HttpStatusCode.OK)
            {
                using (Stream responseStream = tokenResponse.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        var reader = new StreamReader(responseStream);
                        var responseJson = reader.ReadToEnd();
                        var user = JsonConvert.DeserializeObject<YammerUser>(responseJson);

                        var data = new Dictionary<string, string>();

                        data.Add("id", user.id.ToString());
                        data.Add("name", user.full_name);
                        data.Add("email", user.contact.email_addresses[0].address);
                        data.Add("jobTitle", user.job_title);
                        data.Add("location", user.location);
                        data.Add("mugshot", user.mugshot_url);
                        data.Add("network", user.network_name);
                        data.Add("profile", user.web_url);

                        Debug.WriteLine("QueryAccessToken() returned {0} items", data.Count);

                        return data;
                    }
                }
            }
            Debug.WriteLine("GetUserData() returned null");
            return null;
        }
        /// <summary>
        /// The get service login url.
        /// </summary>
        /// <param name="returnUrl">
        /// The return url.
        /// </param>
        /// <returns>An absolute URI.</returns>
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            var test = HttpUtility.ParseQueryString(returnUrl.Query);
            

            var builder = new UriBuilder(AuthorizationEndpoint);
            builder.AppendQueryArgument("client_id", this.clientId);
            builder.AppendQueryArgument("redirect_uri", returnUrl.GetLeftPart(UriPartial.Path));
            builder.AppendQueryArgument("state", returnUrl.Query);
            // builder.AppendQueryArgument("redirect_uri", returnUrl.ToString());
            builder.AppendQueryArgument("response_type", "code");
            builder.AppendQueryArgument("scope", this.realm);

            return builder.Uri;
        }
 private Uri GetServiceLoginUrl2(Uri returnUrl, string service = null)
 {
     var builder = new UriBuilder(AuthorizationEndpoint);
     builder.AppendQueryArgument("client_id", this.clientId);
     builder.AppendQueryArgument("redirect_uri", returnUrl.AbsoluteUri);
     builder.AppendQueryArgument("service", service ?? Service);
     var session = HttpContext.Current.Session;
     if (session["account_id"] != null && session["singly_accesstoken"] != null)
     {
         builder.AppendQueryArgument("account", session["account_id"].ToString());
         builder.AppendQueryArgument("access_token", session["singly_accesstoken"].ToString());
     }
     return builder.Uri;
 }