/// <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)
        {
            var uriBuilder = new UriBuilder(AccessTokenServiceEndpoint);

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

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

            uriBuilder.AppendQueryArgs(args);

            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("Accept", "application/json");

                var text = webClient.UploadString(uriBuilder.Uri, string.Empty);
                if (string.IsNullOrEmpty(text))
                    return null;

                var data = JObject.Parse(text);
                return data["access_token"].Value<string>();
            }
        }
Example #2
0
		/// <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.AppendQueryArgs(
				new Dictionary<string, string> {
					{ "client_id", this.appId },
					{ "redirect_uri", returnUrl.AbsoluteUri }
				});
			return builder.Uri;
		}
 public void AddCallbackArgumentClearsPreviousArgument()
 {
     UriBuilder returnToWithArgs = new UriBuilder(this.returnTo);
     returnToWithArgs.AppendQueryArgs(new Dictionary<string, string> { { "p1", "v1" } });
     this.returnTo = returnToWithArgs.Uri;
     IAuthenticationRequest_Accessor authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
     authRequest.AddCallbackArguments("p1", "v2");
     var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage;
     NameValueCollection query = HttpUtility.ParseQueryString(req.ReturnTo.Query);
     Assert.AreEqual("v2", query["p1"]);
 }
		/// <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 builder = new UriBuilder(AuthorizationEndpoint);
			builder.AppendQueryArgs(
				new Dictionary<string, string> {
					{ "client_id", this.appId },
					{ "scope", "wl.basic" },
					{ "response_type", "code" },
					{ "redirect_uri", returnUrl.AbsoluteUri },
				});

			return builder.Uri;
		}
Example #5
0
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            var builder = new UriBuilder(_authorizationEndpoint);
            builder.AppendQueryArgs(
                new Dictionary<string, string>
                {
                    {"response_type", "code"},
                    {"redirect_uri", returnUrl.AbsoluteUri},
                    {"scope", "https://www.googleapis.com/auth/userinfo.email"},
                    {"client_id", _clientId}
                });

            return builder.Uri;
        }
Example #6
0
 protected override Uri GetServiceLoginUrl(Uri returnUrl)
 {
     if (returnUrl == null) throw new ArgumentNullException("returnUrl");
     var builder = new UriBuilder("http://www.odnoklassniki.ru/oauth/authorize");
     var args = new Dictionary<string, string>
         {
             {"client_id", AppId},
             {"redirect_uri", returnUrl.AbsoluteUri},
             {"scope", ""},
             {"response_type", "code"}
         };
     builder.AppendQueryArgs(args);
     return builder.Uri;
 }
		internal static HttpRequestMessage CreateHttpRequestInfo(HttpMethod method, IDictionary<string, string> fields) {
			var result = new HttpRequestMessage() { Method = method };
			var requestUri = new UriBuilder(DefaultUrlForHttpRequestInfo);
			if (method == HttpMethod.Post) {
				result.Content = new FormUrlEncodedContent(fields);
			} else if (method == HttpMethod.Get) {
				requestUri.AppendQueryArgs(fields);
			} else {
				throw new ArgumentOutOfRangeException("method", method, "Expected POST or GET");
			}

			result.RequestUri = requestUri.Uri;
			return result;
		}
        /// <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(AuthorizationServiceEndpoint);

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

            args.Add("client_id", this.appId);
            args.Add("response_type", "code");
            args.Add("redirect_uri", returnUrl.AbsoluteUri);

            builder.AppendQueryArgs(args);

            return builder.Uri;
        }
Example #9
0
 protected override Uri GetServiceLoginUrl(Uri returnUrl)
 {
     if (returnUrl == null) throw new ArgumentNullException("returnUrl");
     var builder = new UriBuilder("https://oauth.vk.com/authorize");
     var args = new Dictionary<string, string>
         {
             {"client_id", AppId},
             {"redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri)},
             {"display", "page"},
             {"response_type", "code"},
             {"scope", String.Join(",", Scopes)},
         };
     builder.AppendQueryArgs(args);
     return builder.Uri;
 }
Example #10
0
 protected override Uri GetServiceLoginUrl(Uri returnUrl)
 {
     UriBuilder builder = new UriBuilder("https://oauth.live.com/authorize");
     Dictionary<string, string> args = new Dictionary<string, string>();
     args.Add("client_id", this.clientId);
     args.Add("scope", "wl.emails");
     args.Add("response_type", "code");
     #if DEBUG
     args.Add("redirect_uri", (new Uri(returnUrl.AbsoluteUri.Replace("localhost", "mstestdomain.com"))).AbsoluteUri);
     #else
     args.Add("redirect_uri", returnUrl.AbsoluteUri);
     #endif
     builder.AppendQueryArgs(args);
     return builder.Uri;
 }
        public void GetReturnToArgumentAndNames()
        {
            UriBuilder returnToBuilder = new UriBuilder(this.response.ReturnTo);
            returnToBuilder.AppendQueryArgs(new Dictionary<string, string> { { "a", "b" } });
            this.request.ReturnTo = returnToBuilder.Uri;

            // First pretend that the return_to args were signed.
            this.response = new IndirectSignedResponse(this.request);
            this.response.ReturnToParametersSignatureValidated = true;
            Assert.AreEqual(1, this.response.GetReturnToParameterNames().Count());
            Assert.IsTrue(this.response.GetReturnToParameterNames().Contains("a"));
            Assert.AreEqual("b", this.response.GetReturnToArgument("a"));

            // Now simulate them NOT being signed.  They should still be visible at this level.
            this.response = new IndirectSignedResponse(this.request);
            this.response.ReturnToParametersSignatureValidated = false;
            Assert.AreEqual(1, this.response.GetReturnToParameterNames().Count());
            Assert.IsTrue(this.response.GetReturnToParameterNames().Contains("a"));
            Assert.AreEqual("b", this.response.GetReturnToArgument("a"));
        }
        public void GetCallbackArguments()
        {
            PositiveAssertionResponse assertion = this.GetPositiveAssertion();
            var rp = CreateRelyingParty();

            UriBuilder returnToBuilder = new UriBuilder(assertion.ReturnTo);
            returnToBuilder.AppendQueryArgs(new Dictionary<string, string> { { "a", "b" } });
            assertion.ReturnTo = returnToBuilder.Uri;
            var authResponse = new PositiveAuthenticationResponse(assertion, rp);

            // First pretend that the return_to args were signed.
            assertion.ReturnToParametersSignatureValidated = true;
            Assert.AreEqual(1, authResponse.GetCallbackArguments().Count);
            Assert.IsTrue(authResponse.GetCallbackArguments().ContainsKey("a"));
            Assert.AreEqual("b", authResponse.GetCallbackArgument("a"));

            // Now simulate them NOT being signed.
            assertion.ReturnToParametersSignatureValidated = false;
            Assert.AreEqual(0, authResponse.GetCallbackArguments().Count);
            Assert.IsFalse(authResponse.GetCallbackArguments().ContainsKey("a"));
            Assert.IsNull(authResponse.GetCallbackArgument("a"));
        }
Example #13
0
        /// <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 builder = new UriBuilder(GetUsersEndpoint);
            builder.AppendQueryArgs(
                new Dictionary<string, string> {
					{ "uid", _accessTokenResponse.user_id.ToString(CultureInfo.InvariantCulture) },
					{ "access_token", _accessTokenResponse.access_token }
				});


            using (var client = new WebClient { Encoding = Encoding.UTF8 })
            {
                string data = client.DownloadString(builder.Uri);
                if (string.IsNullOrEmpty(data))
                {
                    return null;
                }
                var response = JsonConvert.DeserializeObject<VkApiResponse>(data);
                if (response != null && response.response.Length == 1)
                {
                    var userData = new Dictionary<string, string>();
                    userData.AddItemIfNotEmpty("id", response.response[0].uid);
                    userData.AddItemIfNotEmpty("name", response.response[0].first_name + " " + response.response[0].last_name);

                    return userData;
                }
            }
            return new Dictionary<string, string>();
        }
Example #14
0
        /// <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.AppendQueryArgs(
                new Dictionary<string, string> {
					{ "client_id", _appId },
					{ "redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri) },
					{ "client_secret", _appSecret },
					{ "code", authorizationCode },
					{ "scope", "" },
				});

            using (var client = new WebClient())
            {
                string data = client.DownloadString(builder.Uri);
                if (string.IsNullOrEmpty(data))
                {
                    return null;
                }
                _accessTokenResponse = JsonConvert.DeserializeObject<VkAccessTokenResponse>(data);
                if (_accessTokenResponse != null)
                {
                    return _accessTokenResponse.access_token;
                }

                return string.Empty;
            }
        }
        private static string QueryAccessToken(string tokenEndpoint, string consumerKey, string consumerSecret, Uri returnUrl, string authorizationCode)
        {
            // Note: Facebook doesn't like us to url-encode the redirect_uri value
            var builder = new UriBuilder(tokenEndpoint);
            builder.AppendQueryArgs(
                new Dictionary<string, string> {
                    { "client_id", consumerKey },
                    { "redirect_uri", returnUrl.AbsoluteUri.NormalizeHexEncoding() },
                    { "client_secret", consumerSecret },
                    { "code", authorizationCode },
                    { "scope", "email" },
                });

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

                var parsedQueryString = HttpUtility.ParseQueryString(data);
                return parsedQueryString["access_token"];
            }
        }
        public static void RequestAuthentication(string authEndpoint, Uri returnUrl, string consumerKey, RedirectMethod redirectMethod)
        {
            var builder = new UriBuilder(authEndpoint);

            builder.AppendQueryArgs(
                new Dictionary<string, string> {
                    { "client_id", consumerKey },
                    { "redirect_uri", returnUrl.AbsoluteUri },
                    { "scope", "email" },
                });

            redirectMethod(builder.Uri.AbsoluteUri, true);
        }
        /// <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(UserInfoServiceEndpoint.Replace("{{user-id}}", currentUserId));

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

            args.Add("access_token", accessToken);

            uriBuilder.AppendQueryArgs(args);

            using (var webClient = new WebClient())
            {
                webClient.Encoding = Encoding.UTF8;

                var text = webClient.DownloadString(uriBuilder.Uri);
                if (string.IsNullOrEmpty(text))
                    return null;

                var data = JObject.Parse(text);

                var user = data["data"];

                var names = user["full_name"].Value<string>().Split(' ');

                var dictionary = new Dictionary<string, string>();
                dictionary.AddItemIfNotEmpty("id", user["id"].Value<string>());
                dictionary.AddItemIfNotEmpty("firstName", names.Any() ? names.First() : data["username"].Value<string>());
                dictionary.AddItemIfNotEmpty("lastName", names.Count() > 1 ? names.Last() : string.Empty);
                return dictionary;
            }
        }
Example #18
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;
				}
			}
		}
Example #19
0
        /// <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.AppendQueryArgs(
                new Dictionary<string, string> {
                    { "client_id", _appId },
                    { "redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri) },
                    { "client_secret", _appSecret },
                    { "code", authorizationCode },
                    { "scope", String.Join(",", Scopes) },
                });

            using (var client = new WebClient())
            {
                string data;
                try
                {
                    data = client.DownloadString(builder.Uri);
                }
                catch (WebException)
                {
                    //try once again
                    data = client.DownloadString(builder.Uri);
                }
                if (string.IsNullOrEmpty(data))
                {
                    return null;
                }

                var parsedQueryString = HttpUtility.ParseQueryString(data);
                return parsedQueryString["access_token"];
            }
        }
		public async Task AddCallbackArgumentClearsPreviousArgument() {
			UriBuilder returnToWithArgs = new UriBuilder(this.returnTo);
			returnToWithArgs.AppendQueryArgs(new Dictionary<string, string> { { "p1", "v1" } });
			this.returnTo = returnToWithArgs.Uri;
			var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId);
			authRequest.AddCallbackArguments("p1", "v2");
			var response = (HttpResponseMessageWithOriginal)await authRequest.GetRedirectingResponseAsync(CancellationToken.None);
			var req = (SignedResponseRequest)response.OriginalMessage;
			NameValueCollection query = HttpUtility.ParseQueryString(req.ReturnTo.Query);
			Assert.AreEqual("v2", query["p1"]);
		}
Example #21
0
        /// <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 builder = new UriBuilder(AuthorizationEndpoint);

            builder.AppendQueryArgs(
                new Dictionary<string, string>
                    {
                        {"grant_type", "authorization_code"},
                        {"client_id", this.appId},
                        {"client_secret", this.appSecret},
                        //{ "scope", string.Join(" ", this.requestedScopes) },
                        {"response_type", "code"},
                        {"redirect_uri", returnUrl.AbsoluteUri},
                    });

            return builder.Uri;
        }
		/// <summary>
		/// Generates the authentication requests that can satisfy the requirements of some OpenID Identifier.
		/// </summary>
		/// <param name="userSuppliedIdentifier">
		/// The Identifier supplied by the user.  This may be a URL, an XRI or i-name.
		/// </param>
		/// <param name="realm">
		/// The shorest URL that describes this relying party web site's address.
		/// For example, if your login page is found at https://www.example.com/login.aspx,
		/// your realm would typically be https://www.example.com/.
		/// </param>
		/// <returns>
		/// A sequence of authentication requests, any of which constitutes a valid identity assertion on the Claimed Identifier.
		/// Never null, but may be empty.
		/// </returns>
		/// <remarks>
		/// <para>Any individual generated request can satisfy the authentication.  
		/// The generated requests are sorted in preferred order.
		/// Each request is generated as it is enumerated to.  Associations are created only as
		/// <see cref="IAuthenticationRequest.RedirectingResponse"/> is called.</para>
		/// <para>No exception is thrown if no OpenID endpoints were discovered.  
		/// An empty enumerable is returned instead.</para>
		/// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para>
		/// </remarks>
		/// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception>
		public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm) {
			Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
			Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
			Contract.Requires<ArgumentNullException>(realm != null);
			Contract.Ensures(Contract.Result<IEnumerable<IAuthenticationRequest>>() != null);

			// This next code contract is a BAD idea, because it causes each authentication request to be generated
			// at least an extra time.
			////Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<IAuthenticationRequest>>(), el => el != null));

			// Build the return_to URL
			UriBuilder returnTo = new UriBuilder(this.Channel.GetRequestFromContext().UrlBeforeRewriting);

			// Trim off any parameters with an "openid." prefix, and a few known others
			// to avoid carrying state from a prior login attempt.
			returnTo.Query = string.Empty;
			NameValueCollection queryParams = this.Channel.GetRequestFromContext().QueryStringBeforeRewriting;
			var returnToParams = new Dictionary<string, string>(queryParams.Count);
			foreach (string key in queryParams) {
				if (!IsOpenIdSupportingParameter(key) && key != null) {
					returnToParams.Add(key, queryParams[key]);
				}
			}
			returnTo.AppendQueryArgs(returnToParams);

			return this.CreateRequests(userSuppliedIdentifier, realm, returnTo.Uri);
		}
Example #23
0
        /// <summary>
        /// Generates the authentication requests that can satisfy the requirements of some OpenID Identifier.
        /// </summary>
        /// <param name="userSuppliedIdentifier">
        /// The Identifier supplied by the user.  This may be a URL, an XRI or i-name.
        /// </param>
        /// <param name="realm">
        /// The shorest URL that describes this relying party web site's address.
        /// For example, if your login page is found at https://www.example.com/login.aspx,
        /// your realm would typically be https://www.example.com/.
        /// </param>
        /// <returns>
        /// A sequence of authentication requests, any of which constitutes a valid identity assertion on the Claimed Identifier.
        /// Never null, but may be empty.
        /// </returns>
        /// <remarks>
        /// <para>Any individual generated request can satisfy the authentication.  
        /// The generated requests are sorted in preferred order.
        /// Each request is generated as it is enumerated to.  Associations are created only as
        /// <see cref="IAuthenticationRequest.RedirectingResponse"/> is called.</para>
        /// <para>No exception is thrown if no OpenID endpoints were discovered.  
        /// An empty enumerable is returned instead.</para>
        /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para>
        /// </remarks>
        /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception>
        public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm)
        {
            Contract.Requires(userSuppliedIdentifier != null);
            Contract.Requires(realm != null);
            Contract.Ensures(Contract.Result<IEnumerable<IAuthenticationRequest>>() != null);
            ErrorUtilities.VerifyHttpContext();

            // Build the return_to URL
            UriBuilder returnTo = new UriBuilder(this.Channel.GetRequestFromContext().UrlBeforeRewriting);

            // Trim off any parameters with an "openid." prefix, and a few known others
            // to avoid carrying state from a prior login attempt.
            returnTo.Query = string.Empty;
            NameValueCollection queryParams = this.Channel.GetRequestFromContext().QueryStringBeforeRewriting;
            var returnToParams = new Dictionary<string, string>(queryParams.Count);
            foreach (string key in queryParams) {
                if (!IsOpenIdSupportingParameter(key) && key != null) {
                    returnToParams.Add(key, queryParams[key]);
                }
            }
            returnTo.AppendQueryArgs(returnToParams);

            return this.CreateRequests(userSuppliedIdentifier, realm, returnTo.Uri);
        }
Example #24
0
 protected override Uri GetServiceLoginUrl(Uri returnUrl)
 {
     UriBuilder builder = new UriBuilder("https://www.facebook.com/dialog/oauth");
     Dictionary<string, string> args = new Dictionary<string, string>();
     args.Add("client_id", this.appId);
     args.Add("redirect_uri", returnUrl.AbsoluteUri);
     args.Add("scope", "email");
     builder.AppendQueryArgs(args);
     return builder.Uri;
 }
Example #25
0
        protected override IDictionary<string, string> GetUserData(string accessToken)
        {
            if (accessToken == null) throw new ArgumentNullException("accessToken");
            var data = HttpContext.Current.Session["OdnoklassnikiOAuthProvider.Token"] as OdnoklassnikiTokenResponse;
            if (data == null || data.AccessToken != accessToken)
                return null;
            var res = new Dictionary<string, string>();
            var builder = new UriBuilder("http://api.odnoklassniki.ru/fb.do");
            //$curl = curl_init('http://api.odnoklassniki.ru/fb.do?access_token=' . $auth['access_token'] .
            //'&application_key=' . $AUTH['application_key'] . '&method=users.getCurrentUser&sig=' .
            //md5('application_key=' . $AUTH['application_key'] . 'method=users.getCurrentUser' . md5($auth['access_token'] . $AUTH['client_secret'])));

            var sign = String.Format("{0}{1}", accessToken, AppSecret).CalculateMd5Hash().ToLower();
            sign = String.Format("application_key={0}method=users.getCurrentUser{1}", AppPublic, sign).CalculateMd5Hash().ToLower();
            var args = new Dictionary<string, string>
                {
                    {"method", "users.getCurrentUser"},
                    {"access_token", accessToken},
                    {"application_key", AppPublic},
                    {"sig", sign},
                };
            builder.AppendQueryArgs(args);
            using (var client = new WebClient())
            {
                using (var stream = client.OpenRead(builder.Uri))
                {
                    var serializer = new DataContractJsonSerializer(typeof (OdnoklassnikiDataItem));
                    if (stream != null)
                    {
                        var info = (OdnoklassnikiDataItem) serializer.ReadObject(stream);
                        if (info != null)
                        {
                            var item = info;
                            res.AddItemIfNotEmpty("id", item.UserId);
                            res.AddItemIfNotEmpty("username", item.UserId);
                            res.AddItemIfNotEmpty("name",
                                                  item.Name ??
                                                  (((item.FirstName ?? "") + " " + (item.LastName ?? "")).Trim()));
                            res.AddItemIfNotEmpty("birthday", item.Birthdate);
                            res.AddItemIfNotEmpty("gender", item.Sex);
                            res.AddItemIfNotEmpty("link", String.Format("http://odnoklassniki.ru/profile/{0}", item.UserId));
                            res.AddItemIfNotEmpty("photo", item.Photo ?? item.Photo2);
                        }
                    }
                }
            }
            return res;
        }
Example #26
0
 protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
 {
     UriBuilder builder = new UriBuilder("https://graph.facebook.com/oauth/access_token");
     Dictionary<string, string> args = new Dictionary<string, string>();
     args.Add("client_id", this.appId);
     args.Add("redirect_uri", NormalizeHexEncoding(returnUrl.AbsoluteUri));
     args.Add("client_secret", this.appSecret);
     args.Add("code", authorizationCode);
     builder.AppendQueryArgs(args);
     using (WebClient client = new WebClient())
     {
         string str = client.DownloadString(builder.Uri);
         if (string.IsNullOrEmpty(str))
         {
             return null;
         }
         return HttpUtility.ParseQueryString(str)["access_token"];
     }
 }
Example #27
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);
					}
				}
			}
		}
Example #28
0
        /// <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>
        /// <returns>The service login URL.</returns>
        /// <param name="returnUrl">Return URL.</param>
        protected override Uri GetServiceLoginUrl(Uri returnUrl)
        {
            var scopes = requestedScopes.Select(x => !x.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? scopeUri + x : x);
            UriBuilder builder = new UriBuilder(authorizationEndpoint);
            builder.AppendQueryArgs(new Dictionary<string, string>()
            {
                { "response_type", "code" },
                { "client_id", this.appId },
                { "scope", string.Join(" ", scopes) },
                { "redirect_uri", returnUrl.GetLeftPart(UriPartial.Path) },
                { "state", returnUrl.Query.Substring(1) },
            });

            return builder.Uri;
        }
		/// <summary>
		/// Applies OAuth authorization to the specified request.
		/// This method is applied automatically to outbound requests that use this message handler instance.
		/// However this method may be useful for obtaining the OAuth 1.0 signature without actually sending the request.
		/// </summary>
		/// <param name="request">The request.</param>
		public void ApplyAuthorization(HttpRequestMessage request) {
			Requires.NotNull(request, "request");

			var oauthParameters = this.GetOAuthParameters();
			string signature = this.GetSignature(request, oauthParameters);
			oauthParameters.Add("oauth_signature", signature);

			// Add parameters and signature to request.
			switch (this.Location) {
				case OAuthParametersLocation.AuthorizationHttpHeader:
					// Some oauth parameters may have been put in the query string of the original message.
					// We want to move any that we find into the authorization header.
					oauthParameters.Add(ExtractOAuthParametersFromQueryString(request));

					request.Headers.Authorization = new AuthenticationHeaderValue(Protocol.AuthorizationHeaderScheme, MessagingUtilities.AssembleAuthorizationHeader(oauthParameters.AsKeyValuePairs()));
					break;
				case OAuthParametersLocation.QueryString:
					var uriBuilder = new UriBuilder(request.RequestUri);
					uriBuilder.AppendQueryArgs(oauthParameters.AsKeyValuePairs());
					request.RequestUri = uriBuilder.Uri;
					break;
			}
		}
Example #30
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)
        {
            // Note: Facebook doesn't like us to url-encode the redirect_uri value
            var builder = new UriBuilder(TokenEndpoint);
            builder.AppendQueryArgs(new Dictionary<string, string>()
            {
                { "client_id", this.appId },
                { "redirect_uri", UriHelper.NormalizeHexEncoding(returnUrl.AbsoluteUri) },
                { "client_secret", this.appSecret },
                { "code", authorizationCode },
                { "scope", this.scope }
            });

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

                var parsedQueryString = HttpUtility.ParseQueryString(data);
                return parsedQueryString["access_token"];
            }
        }