コード例 #1
0
        private AccessGrant AuthenticateClient(bool expectParamBasedClientAuthentication, string responseFile)
        {
            OAuth2Template testedOAuth2Template = expectParamBasedClientAuthentication ? oAuth2TemplateParamBasedClientAuthentication : oAuth2Template;

            HttpHeaders responseHeaders = new HttpHeaders();

            responseHeaders.ContentType = MediaType.APPLICATION_JSON;
            MockRestServiceServer mockServer     = MockRestServiceServer.CreateServer(testedOAuth2Template.RestTemplate);
            IRequestActions       requestActions = mockServer.ExpectNewRequest()
                                                   .AndExpectUri(ACCESS_TOKEN_URL)
                                                   .AndExpectMethod(HttpMethod.POST)
                                                   .AndExpectBody((expectParamBasedClientAuthentication ? "client_id=client_id&client_secret=client_secret&" : "") + "grant_type=client_credentials&scope=read%2Cwrite");

            if (!expectParamBasedClientAuthentication)
            {
                requestActions.AndExpectHeader("Authorization", "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=");
            }
            requestActions.AndRespondWith(new AssemblyResource(responseFile, typeof(OAuth2TemplateTests)), responseHeaders);

            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.Scope = "read,write";
#if NET_4_0 || SILVERLIGHT_5
            AccessGrant accessGrant = testedOAuth2Template.AuthenticateClientAsync("read,write").Result;
#else
            AccessGrant accessGrant = testedOAuth2Template.AuthenticateClient("read,write");
#endif
            return(accessGrant);
        }
コード例 #2
0
        private static string BuildAuthUrl(string baseAuthUrl, GrantType grantType, OAuth2Parameters parameters)
        {
            StringBuilder authUrl = new StringBuilder(baseAuthUrl);

            if (grantType == GrantType.AuthorizationCode)
            {
                authUrl.Append("&response_type=code");
            }
            else if (grantType == GrantType.ImplicitGrant)
            {
                authUrl.Append("&response_type=token");
            }
            if (parameters != null)
            {
                foreach (string parameterName in parameters)
                {
                    string parameterNameEncoded = HttpUtils.UrlEncode(parameterName);
                    foreach (string parameterValue in parameters.GetValues(parameterName))
                    {
                        authUrl.AppendFormat("&{0}={1}", parameterNameEncoded, HttpUtils.UrlEncode(parameterValue));
                    }
                }
            }
            return(authUrl.ToString());
        }
コード例 #3
0
 public void BuildAuthorizeUrl_NoScopeInParameters()
 {
     OAuth2Parameters parameters = new OAuth2Parameters();
     parameters.RedirectUrl = "http://www.someclient.com/connect/foo";
     string expected = AUTHORIZE_URL + "?client_id=client_id&response_type=code&redirect_uri=http%3A%2F%2Fwww.someclient.com%2Fconnect%2Ffoo";
     string actual = oAuth2Template.BuildAuthorizeUrl(GrantType.AuthorizationCode, parameters);
     Assert.AreEqual(expected, actual);
 }
コード例 #4
0
	    public void BuildAuthorizeUrl_TokenResponseType() 
        {
            OAuth2Parameters parameters = new OAuth2Parameters();
            parameters.RedirectUrl = "http://www.someclient.com/connect/foo";
            parameters.Scope = "read,write";
            string expected = AUTHORIZE_URL + "?client_id=client_id&response_type=token&redirect_uri=http%3A%2F%2Fwww.someclient.com%2Fconnect%2Ffoo&scope=read%2Cwrite";
		    string actual = oAuth2Template.BuildAuthorizeUrl(GrantType.ImplicitGrant, parameters);
		    Assert.AreEqual(expected, actual);
	    }
コード例 #5
0
 // GET: /Facebook/SignIn
 public ActionResult SignIn()
 {
     OAuth2Parameters parameters = new OAuth2Parameters()
     {
         RedirectUrl = "http://localhost/Facebook/Callback",
         Scope = "publish_stream"
     };
     return Redirect(facebookProvider.OAuthOperations.BuildAuthorizeUrl(GrantType.AuthorizationCode, parameters));
 }
コード例 #6
0
        public void BuildAuthorizeUrl_NoScopeInParameters()
        {
            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.RedirectUrl = "http://www.someclient.com/connect/foo";
            string expected = AUTHORIZE_URL + "?client_id=client_id&response_type=code&redirect_uri=http%3A%2F%2Fwww.someclient.com%2Fconnect%2Ffoo";
            string actual   = oAuth2Template.BuildAuthorizeUrl(GrantType.AuthorizationCode, parameters);

            Assert.AreEqual(expected, actual);
        }
コード例 #7
0
        public void BuildAuthorizeUrl_TokenResponseType()
        {
            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.RedirectUrl = "http://www.someclient.com/connect/foo";
            parameters.Scope       = "read,write";
            string expected = AUTHORIZE_URL + "?client_id=client_id&response_type=token&redirect_uri=http%3A%2F%2Fwww.someclient.com%2Fconnect%2Ffoo&scope=read%2Cwrite";
            string actual   = oAuth2Template.BuildAuthorizeUrl(GrantType.ImplicitGrant, parameters);

            Assert.AreEqual(expected, actual);
        }
コード例 #8
0
 /// <summary>
 /// Constructs the URL to redirect the user to for authentication.
 /// <para/>
 /// The authenticate URL differs from the authorizationUrl slightly in that it does not require the user to authorize the app multiple times.
 /// This provides a better user experience for "Sign in with Provider" scenarios.
 /// </summary>
 /// <param name="grantType">
 /// Specifies whether to use client-side or server-side OAuth flow.
 /// </param>
 /// <param name="parameters">
 /// Authorization parameters needed to build the URL. May be null.
 /// </param>
 /// <returns>The absolute authenticate URL to redirect the user to for authorization.</returns>
 public string BuildAuthenticateUrl(GrantType grantType, OAuth2Parameters parameters)
 {
     if (this.authenticateUrl != null)
     {
         return(BuildAuthUrl(this.authenticateUrl, grantType, parameters));
     }
     else
     {
         return(this.BuildAuthorizeUrl(grantType, parameters));
     }
 }
コード例 #9
0
 public void BuildAuthorizeUrl_AdditionalParameters()
 {
     OAuth2Parameters parameters = new OAuth2Parameters();
     parameters.RedirectUrl = "http://www.someclient.com/connect/foo";
     parameters.Scope = "read,write";
     parameters.Add("display", "touch");
     parameters.Add("anotherparam", "somevalue1");
     parameters.Add("anotherparam", "somevalue2");
     string expected = AUTHORIZE_URL + "?client_id=client_id&response_type=token&redirect_uri=http%3A%2F%2Fwww.someclient.com%2Fconnect%2Ffoo&scope=read%2Cwrite&display=touch&anotherparam=somevalue1&anotherparam=somevalue2";
     string actual = oAuth2Template.BuildAuthorizeUrl(GrantType.ImplicitGrant, parameters);
     Assert.AreEqual(expected, actual);
 }
コード例 #10
0
        public void BuildAuthorizeUrl_AdditionalParameters()
        {
            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.RedirectUrl = "http://www.someclient.com/connect/foo";
            parameters.Scope       = "read,write";
            parameters.Add("display", "touch");
            parameters.Add("anotherparam", "somevalue1");
            parameters.Add("anotherparam", "somevalue2");
            string expected = AUTHORIZE_URL + "?client_id=client_id&response_type=token&redirect_uri=http%3A%2F%2Fwww.someclient.com%2Fconnect%2Ffoo&scope=read%2Cwrite&display=touch&anotherparam=somevalue1&anotherparam=somevalue2";
            string actual   = oAuth2Template.BuildAuthorizeUrl(GrantType.ImplicitGrant, parameters);

            Assert.AreEqual(expected, actual);
        }
コード例 #11
0
		public ActionResult Index()
		{
			var accessGrant = Session["AccessGrant"] as AccessGrant;
			if (accessGrant != null)
			{
				ViewBag.AccessToken = accessGrant.AccessToken;

				return View();
			}

			var parameters = new OAuth2Parameters
			{
				RedirectUrl = CallbackUrl,
				Scope = "no_expiry"
			};
			return Redirect(_stackExchangeProvider.OAuthOperations.BuildAuthorizeUrl(GrantType.AuthorizationCode, parameters));
		}
コード例 #12
0
		public ActionResult Index()
		{
			var accessGrant = Session["AccessGrant"] as AccessGrant;
			if (accessGrant != null)
			{
				//Until explict GitHub endpoints have API bindings, the following
				//method can be employed to consume GitHub endpoints
				var gitHubClient = _gitHubProvider.GetApi(accessGrant.AccessToken);
				var result = gitHubClient.RestOperations.GetForObject<JsonValue>("https://api.github.com/user/repos");

				ViewBag.AccessToken = accessGrant.AccessToken;
				ViewBag.ResultText = result.ToString();

				return View();
			}

			var parameters = new OAuth2Parameters
			{
				RedirectUrl = CallbackUrl,
				Scope = "repo"
			};
			return Redirect(_gitHubProvider.OAuthOperations.BuildAuthorizeUrl(GrantType.AuthorizationCode, parameters));
		}
コード例 #13
0
        public ActionResult Index()
        {
            var accessGrant = Session["AccessGrant"] as AccessGrant;
            if (accessGrant != null)
            {
                //Until explict Elance endpoints have API bindings, the following
                //method can be employed to consume Elance endpoints
                var elanceClient = _elanceProvider.GetApi(accessGrant.AccessToken);
                var result = elanceClient.RestOperations.GetForObject<JsonValue>("http://api.elance.com/api2/profiles/my?access_token=" + accessGrant.AccessToken);

                ViewBag.AccessToken = accessGrant.AccessToken;
                ViewBag.ResultText = result.ToString();

                return View();
            }

            var parameters = new OAuth2Parameters
            {
                RedirectUrl = CallbackUrl,
                Scope = "basicInfo"
            };
            return Redirect(_elanceProvider.OAuthOperations.BuildAuthorizeUrl(GrantType.AuthorizationCode, parameters));
        }
コード例 #14
0
 /// <summary>
 /// Construct the URL to redirect the user to for authentication.
 /// <para/>
 /// The authenticate URL differs from the authorizationUrl slightly in that it does not require the user to authorize the app multiple times.
 /// This provides a better user experience for "Sign in with Provider" scenarios.
 /// </summary>
 /// <param name="grantType">
 /// Specifies whether to use client-side or server-side OAuth flow.
 /// </param>
 /// <param name="parameters">
 /// Authorization parameters needed to build the URL. May be null.
 /// </param>
 /// <returns>The absolute authenticate URL to redirect the user to for authorization.</returns>
 public string BuildAuthenticateUrl(GrantType grantType, OAuth2Parameters parameters)
 {
     if (this.authenticateUrl != null)
     {
         return BuildAuthUrl(this.authenticateUrl, grantType, parameters);
     }
     else
     {
         return this.BuildAuthorizeUrl(grantType, parameters);
     }
 }
コード例 #15
0
 /// <summary>
 /// Construct the URL to redirect the user to for authorization.
 /// </summary>
 /// <param name="grantType">
 /// Specifies whether to use client-side or server-side OAuth flow.
 /// </param>
 /// <param name="parameters">
 /// Authorization parameters needed to build the URL. May be null.
 /// </param>
 /// <returns>
 /// The absolute authorize URL to redirect the user to for authorization.
 /// </returns>
 public string BuildAuthorizeUrl(GrantType grantType, OAuth2Parameters parameters)
 {
     return BuildAuthUrl(this.authorizeUrl, grantType, parameters);
 }
コード例 #16
0
        private AccessGrant AuthenticateClient(bool expectParamBasedClientAuthentication, string responseFile)
        {
            OAuth2Template testedOAuth2Template = expectParamBasedClientAuthentication ? oAuth2TemplateParamBasedClientAuthentication : oAuth2Template;

            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.ContentType = MediaType.APPLICATION_JSON;
            MockRestServiceServer mockServer = MockRestServiceServer.CreateServer(testedOAuth2Template.RestTemplate);
            IRequestActions requestActions = mockServer.ExpectNewRequest()
                .AndExpectUri(ACCESS_TOKEN_URL)
                .AndExpectMethod(HttpMethod.POST)
                .AndExpectBody((expectParamBasedClientAuthentication ? "client_id=client_id&client_secret=client_secret&" : "") + "grant_type=client_credentials&scope=read%2Cwrite");
            if (!expectParamBasedClientAuthentication)
            {
                requestActions.AndExpectHeader("Authorization", "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=");
            }
            requestActions.AndRespondWith(new AssemblyResource(responseFile, typeof(OAuth2TemplateTests)), responseHeaders);

            OAuth2Parameters parameters = new OAuth2Parameters();
            parameters.Scope = "read,write";
#if NET_4_0 || SILVERLIGHT_5
            AccessGrant accessGrant = testedOAuth2Template.AuthenticateClientAsync("read,write").Result;
#else
            AccessGrant accessGrant = testedOAuth2Template.AuthenticateClient("read,write");
#endif
            return accessGrant;
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: nsavga/spring-net-social
        static void Main(string[] args)
        {
            try
            {
                FacebookServiceProvider facebookServiceProvider = new FacebookServiceProvider(FacebookApiId, FacebookApiSecret);

                /* OAuth 'dance' */

                #region Client credentials grant flow
/*
                // Client is acting on its own behalf
#if NET_4_0
                AccessGrant oauthAccessToken = facebookServiceProvider.OAuthOperations.AuthenticateClientAsync().Result;
#else
                AccessGrant oauthAccessToken = facebookServiceProvider.OAuthOperations.AuthenticateClient();
#endif
                string accessToken = oauthAccessToken.AccessToken;
*/
                #endregion

                #region Implicit grant flow

                // Client is acting on behalf of a user (client-side flow)
                OAuth2Parameters parameters = new OAuth2Parameters()
                {
                    RedirectUrl = "https://www.facebook.com/connect/login_success.html",
                    Scope = "offline_access,publish_stream"
                };
                string authorizationUrl = facebookServiceProvider.OAuthOperations.BuildAuthorizeUrl(GrantType.ImplicitGrant, parameters);
                Console.WriteLine("Redirect user to Facebook for authorization: " + authorizationUrl);
                Process.Start(authorizationUrl);
                Console.WriteLine("Enter 'access_token' query string parameter from success url:");
                string accessToken = Console.ReadLine();

                #endregion

                #region Authorization code grant flow
/*
                // Client is acting on behalf of a user (server-side flow)
                OAuth2Parameters parameters = new OAuth2Parameters()
                {
                    RedirectUrl = "https://www.facebook.com/connect/login_success.html",
                    Scope = "offline_access,publish_stream"
                };
                string authorizationUrl = facebookServiceProvider.OAuthOperations.BuildAuthorizeUrl(GrantType.AuthorizationCode, parameters);
                Console.WriteLine("Redirect user to Facebook for authorization: " + authorizationUrl);
                Process.Start(authorizationUrl);
                Console.WriteLine("Enter 'code' query string parameter from callback url:");
                string code = Console.ReadLine();

                Console.Write("Getting access token...");
#if NET_4_0
                AccessGrant oauthAccessToken = facebookServiceProvider.OAuthOperations.ExchangeForAccessAsync(code, "https://www.facebook.com/connect/login_success.html", null).Result;
#else
                AccessGrant oauthAccessToken = doServiceProvider.OAuthOperations.ExchangeForAccess(code, "https://www.facebook.com/connect/login_success.html", null);
#endif
                Console.WriteLine("Done");
                string accessToken = oauthAccessToken.AccessToken;
*/
                #endregion

                /* API */

                IFacebook facebook = facebookServiceProvider.GetApi(accessToken);
                Console.WriteLine("Enter your status message:");
                string message = Console.ReadLine();
                // This will fail with Client credentials grant flow
#if NET_4_0
                facebook.UpdateStatusAsync(message).Wait();
#else
                facebook.UpdateStatus(message);
#endif
                Console.WriteLine("Status updated!");
            }
#if NET_4_0
            catch (AggregateException ae)
            {
                ae.Handle(ex =>
                    {
                        if (ex is HttpResponseException)
                        {
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(((HttpResponseException)ex).GetResponseBodyAsString());
                            return true;
                        }
                        return false;
                    });
            }
#else
            catch (HttpResponseException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.GetResponseBodyAsString());
            }
#endif
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.WriteLine("--- hit <return> to quit ---");
                Console.ReadLine();
            }
        }
コード例 #18
0
        static void Main(string[] args)
        {
            try
            {
                FacebookServiceProvider facebookServiceProvider = new FacebookServiceProvider(FacebookApiId, FacebookApiSecret);

                /* OAuth 'dance' */

                // Authentication using the client-side authorization flow
                OAuth2Parameters parameters = new OAuth2Parameters()
                {
                    RedirectUrl = "https://www.facebook.com/connect/login_success.html",
                    Scope = "offline_access,publish_stream"
                };
                string authorizationUrl = facebookServiceProvider.OAuthOperations.BuildAuthorizeUrl(GrantType.ImplicitGrant, parameters);
                Console.WriteLine("Redirect user to Facebook for authorization: " + authorizationUrl);
                Process.Start(authorizationUrl);
                Console.WriteLine("Enter 'access_token' query string parameter from success url:");
                string accessToken = Console.ReadLine();

                /* API */

                IFacebook facebook = facebookServiceProvider.GetApi(accessToken);
                Console.WriteLine("Enter your status message:");
                string message = Console.ReadLine();
            #if NET_4_0
                facebook.UpdateStatusAsync(message).Wait();
            #else
                facebook.UpdateStatus(message);
            #endif
                Console.WriteLine("Status updated!");
            }
            #if NET_4_0
            catch (AggregateException ae)
            {
                ae.Handle(ex =>
                    {
                        if (ex is HttpResponseException)
                        {
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(((HttpResponseException)ex).GetResponseBodyAsString());
                            return true;
                        }
                        return false;
                    });
            }
            #else
            catch (HttpResponseException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.GetResponseBodyAsString());
            }
            #endif
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.WriteLine("--- hit <return> to quit ---");
                Console.ReadLine();
            }
        }
コード例 #19
0
 private static string BuildAuthUrl(string baseAuthUrl, GrantType grantType, OAuth2Parameters parameters)
 {
     StringBuilder authUrl = new StringBuilder(baseAuthUrl);
     if (grantType == GrantType.AuthorizationCode)
     {
         authUrl.Append("&response_type=code");
     }
     else if (grantType == GrantType.ImplicitGrant)
     {
         authUrl.Append("&response_type=token");
     }
     if (parameters != null)
     {
         foreach (string parameterName in parameters)
         {
             string parameterNameEncoded = HttpUtils.UrlEncode(parameterName);
             foreach (string parameterValue in parameters.GetValues(parameterName))
             {
                 authUrl.AppendFormat("&{0}={1}", parameterNameEncoded, HttpUtils.UrlEncode(parameterValue));
             }
         }
     }
     return authUrl.ToString();
 }
コード例 #20
0
        static void Main(string[] args)
        {
            try
            {
                FacebookServiceProvider facebookServiceProvider = new FacebookServiceProvider(FacebookApiId, FacebookApiSecret);

                /* OAuth 'dance' */

                // Authentication using the client-side authorization flow 
                OAuth2Parameters parameters = new OAuth2Parameters()
                {
                    RedirectUrl = "https://www.facebook.com/connect/login_success.html",
                    Scope = "email, user_relationships,friends_relationships, user_about_me, friends_about_me, user_birthday, friends_birthday, user_hometown, friends_hometown, user_location, friends_location, user_website, friends_website, read_stream"
                };
                string authorizationUrl = facebookServiceProvider.OAuthOperations.BuildAuthorizeUrl(GrantType.ImplicitGrant, parameters);
                Console.WriteLine("Redirect user to Facebook for authorization: " + authorizationUrl);
                Process.Start(authorizationUrl);
                Console.WriteLine("Enter 'access_token' query string parameter from success url:");
                string accessToken = Console.ReadLine();

                /* API */

                IFacebook facebook = facebookServiceProvider.GetApi(accessToken);
                FacebookProfile me = facebook.UserOperations.GetUserProfile();
                DumpProfile("", me);

                string sTestUserID = "splendidcrm";
                TestUserOperations(facebook, sTestUserID);
                TestPlacesOperations(facebook, sTestUserID);
                TestLikeOperations(facebook, sTestUserID);
                TestFriendOperations(facebook, sTestUserID);
                TestFeedOperations(facebook, sTestUserID);
                TestGroupOperations(facebook, sTestUserID);
                TestCommentOperations(facebook, sTestUserID);
                TestEventOperations(facebook, sTestUserID);
                TestMediaOperations(facebook, sTestUserID);
                TestPageOperations(facebook, sTestUserID);
                TestQuestionOperations(facebook, sTestUserID);
                TestOpenGraphOperations(facebook, sTestUserID);
                TestFqlOperations(facebook, sTestUserID);
            }
#if NET_4_0
			catch (AggregateException ae)
			{
				ae.Handle(ex =>
					{
						if (ex is Spring.Rest.Client.HttpResponseException)
						{
							Console.WriteLine(ex.Message);
							Console.WriteLine(((Spring.Rest.Client.HttpResponseException)ex).GetResponseBodyAsString());
							return true;
						}
						return false;
					});
			}
#else
            catch (Spring.Rest.Client.HttpResponseException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.GetResponseBodyAsString());
            }
#endif
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.WriteLine("--- hit <return> to quit ---");
                Console.ReadLine();
            }
        }
コード例 #21
0
 /// <summary>
 /// Constructs the URL to redirect the user to for authorization.
 /// </summary>
 /// <param name="grantType">
 /// Specifies whether to use client-side or server-side OAuth flow.
 /// </param>
 /// <param name="parameters">
 /// Authorization parameters needed to build the URL. May be null.
 /// </param>
 /// <returns>
 /// The absolute authorize URL to redirect the user to for authorization.
 /// </returns>
 public string BuildAuthorizeUrl(GrantType grantType, OAuth2Parameters parameters)
 {
     return(BuildAuthUrl(this.authorizeUrl, grantType, parameters));
 }