Exemplo n.º 1
0
        protected void identifierBox_LoggedIn(object sender, OpenIdEventArgs e)
        {
            State.FetchResponse = e.Response.GetExtension <FetchResponse>();

            ServiceProviderDescription serviceDescription = new ServiceProviderDescription {
                AccessTokenEndpoint      = new MessageReceivingEndpoint(new Uri(e.Response.Provider.Uri, "/access_token.ashx"), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest),
                TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
            };
            var consumer = new WebConsumerOpenIdRelyingParty(serviceDescription, Global.OwnSampleOPHybridTokenManager);

            AuthorizedTokenResponse accessToken = consumer.ProcessUserAuthorization(e.Response);

            if (accessToken != null)
            {
                this.MultiView1.SetActiveView(this.AuthorizationGiven);

                // At this point, the access token would be somehow associated with the user
                // account at the RP.
                ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken);
            }
            else
            {
                this.MultiView1.SetActiveView(this.AuthorizationDenied);
            }

            // Avoid the redirect
            e.Cancel = true;
        }
Exemplo n.º 2
0
        // A OAuth handler when accessToken and accessTokenSecrets are known
        private static HttpMessageHandler OAuthHandlerWithExistingToken(String requestTokenURL,
                                                                        String authorizationTokenURL,
                                                                        String accessTokenURL,
                                                                        String consumerKey,
                                                                        String consumerSecret,
                                                                        String accessToken,
                                                                        String accessTokenSecret)
        {
            ServiceProviderDescription serviceDescription = new ServiceProviderDescription();

            serviceDescription.AccessTokenEndpoint       = new MessageReceivingEndpoint(new Uri(accessTokenURL), HttpDeliveryMethods.PostRequest);
            serviceDescription.ProtocolVersion           = ProtocolVersion.V10a;
            serviceDescription.RequestTokenEndpoint      = new MessageReceivingEndpoint(new Uri(requestTokenURL), HttpDeliveryMethods.PostRequest);
            serviceDescription.TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() };
            serviceDescription.UserAuthorizationEndpoint = new MessageReceivingEndpoint(new Uri(authorizationTokenURL), HttpDeliveryMethods.PostRequest);

            TokenManager tokenManager = new TokenManager(consumerKey, consumerSecret);

            // Here we add the known token info
            tokenManager.AddKnownAccessTokens(accessToken, accessTokenSecret);

            WebConsumer consumer = new WebConsumer(serviceDescription, tokenManager);

            DesktopConsumer desktopConsumer = new DesktopConsumer(serviceDescription, tokenManager);

            return(consumer.CreateAuthorizingHandler(accessToken, CreateSSLHandler()));
        }
        public LucidChartUser Verify(string oauth_token, string oauth_verifier)
        {
            ServiceProviderDescription desc = new ServiceProviderDescription
            {
                RequestTokenEndpoint      = new MessageReceivingEndpoint(lucidBaseChartUrl + "oauth/requestToken", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
                UserAuthorizationEndpoint = new MessageReceivingEndpoint(lucidBaseChartUrl + "oauth/authorize", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
                AccessTokenEndpoint       = new MessageReceivingEndpoint(lucidBaseChartUrl + "oauth/accessToken?oauth_verifier=" + Uri.EscapeDataString(oauth_verifier), HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
                TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
                ProtocolVersion           = ProtocolVersion.V10a
            };

            var lucid = new WebConsumer(desc, token);

            var accessTokenResponse = lucid.ProcessUserAuthorization();

            if (accessTokenResponse != null)
            {
                string accessToken = accessTokenResponse.AccessToken;
                string secret      = lucid.TokenManager.GetTokenSecret(accessToken);

                return(new LucidChartUser()
                {
                    Token = accessToken, Secret = secret
                });

                /*HttpWebRequest req = lucid.PrepareAuthorizedRequest(new MessageReceivingEndpoint(lucidBaseChartUrl + "documents/describe/49db-4974-4f156c2b-a802-796b0a48117a", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), accessToken);
                 * req.ContentType = "application/xml";
                 * return new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd();*/
            }

            return(null);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes the <see cref="serviceProvider"/> field if it has not yet been initialized.
        /// </summary>
        private static void EnsureInitialized()
        {
            if (serviceProvider == null)
            {
                lock (initializerLock)
                {
                    if (serviceDescription == null)
                    {
                        var postEndpoint = new MessageReceivingEndpoint(new Uri(Utilities.ApplicationRoot, "OAuth.ashx"), HttpDeliveryMethods.PostRequest);
                        var getEndpoint  = new MessageReceivingEndpoint(postEndpoint.Location, HttpDeliveryMethods.GetRequest);
                        serviceDescription = new ServiceProviderDescription
                        {
                            TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
                            RequestTokenEndpoint      = postEndpoint,
                            AccessTokenEndpoint       = postEndpoint,
                            UserAuthorizationEndpoint = getEndpoint,
                        };
                    }

                    if (tokenManager == null)
                    {
                        tokenManager = new OAuthServiceProviderTokenManager();
                    }

                    if (serviceProvider == null)
                    {
                        serviceProvider = new ServiceProvider(serviceDescription, tokenManager);
                    }
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DotNetOpenAuthWebConsumer"/> class.
        /// </summary>
        /// <param name="serviceDescription">
        /// The service description.
        /// </param>
        /// <param name="tokenManager">
        /// The token manager.
        /// </param>
        public DotNetOpenAuthWebConsumer(ServiceProviderDescription serviceDescription, IConsumerTokenManager tokenManager)
        {
            Requires.NotNull(serviceDescription, "serviceDescription");
            Requires.NotNull(tokenManager, "tokenManager");

            this.webConsumer = new WebConsumer(serviceDescription, tokenManager);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            var providerDesc = new ServiceProviderDescription()
            {
                RequestTokenEndpoint      = new MessageReceivingEndpoint("http://localhost:8008/noop", HttpDeliveryMethods.PostRequest),
                AccessTokenEndpoint       = new MessageReceivingEndpoint("http://localhost:8008/noop", HttpDeliveryMethods.PostRequest),
                UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://localhost:8008/noop", HttpDeliveryMethods.PostRequest),
                ProtocolVersion           = ProtocolVersion.V10a,
                TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }
            };

            var consumerKey    = "dotnet-test-key";
            var consumerSecret = File.ReadAllText("..\\..\\keys\\8008\\8080\\" + consumerKey);

            var zeroLeggedWebConsumer = new DotNetOpenAuth.OAuth.WebConsumer(providerDesc, new ZeroLeggedTokenManager(consumerKey, consumerSecret));

            var endpoint    = new MessageReceivingEndpoint("http://localhost:8008/job?query=parameters&also=good", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest);
            var httpRequest = zeroLeggedWebConsumer.PrepareAuthorizedRequest(endpoint, "DUMMY", new Dictionary <String, String>()
            {
                { "are", "post" },
                { "parameters", "handled" },
            });

            var response        = httpRequest.GetResponse();
            var responseContent = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();

            Console.Out.WriteLine(responseContent);
        }
Exemplo n.º 7
0
        protected void identifierBox_LoggedIn(object sender, OpenIdEventArgs e)
        {
            this.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct => {
                State.FetchResponse = e.Response.GetExtension <FetchResponse>();

                var serviceDescription = new ServiceProviderDescription {
                    TokenRequestEndpoint = new Uri(e.Response.Provider.Uri, "/access_token.ashx"),
                };
                var consumer                    = CreateConsumer();
                consumer.ServiceProvider        = serviceDescription;
                AccessTokenResponse accessToken = await consumer.ProcessUserAuthorizationAsync(e.Response);
                if (accessToken != null)
                {
                    this.MultiView1.SetActiveView(this.AuthorizationGiven);

                    // At this point, the access token would be somehow associated with the user
                    // account at the RP.
                    ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken);
                }
                else
                {
                    this.MultiView1.SetActiveView(this.AuthorizationDenied);
                }

                // Avoid the redirect
                e.Cancel = true;
            }));
        }
Exemplo n.º 8
0
        private TwitterApi(string consumerKey, string consumerSecret,
                           string accessToken, string tokenSecret, TokenType tokenType, ApiVersion apiVersion = ApiVersion.V1)
        {
            var consumerCredential = new ConsumerCredential(consumerKey, consumerSecret);

            consumerCredential.SetToken(accessToken, tokenSecret, tokenType);

            var serviceProviderDescription = new ServiceProviderDescription(
                new OAuthEndPoint("https://api.twitter.com/oauth/request_token"),
                new OAuthEndPoint("https://api.twitter.com/oauth/authorize", HttpMethod.Get),
                new OAuthEndPoint("https://api.twitter.com/oauth/access_token"),
                ProtocolVersion.V10A);

            this._OAuth       = new OAuth(consumerCredential, serviceProviderDescription);
            this._OAuth.Realm = ApiBaseUri;
            this._OAuth.Proxy = null;

            this.ApiVersion = apiVersion;

            this._Configuration = new TwitterConfiguration();

            this._Timer = new Timer(_ =>
            {
                var newConfig = this.RetrieveConfiguration();
                if (newConfig != null)
                {
                    Interlocked.Exchange(ref this._Configuration, newConfig);
                }
            }, null, 1000, 1000 * 3600 * 24);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Records the feature and dependency use.
        /// </summary>
        /// <param name="value">The consumer or service provider.</param>
        /// <param name="service">The service.</param>
        /// <param name="tokenManager">The token manager.</param>
        /// <param name="nonceStore">The nonce store.</param>
        internal static void RecordFeatureAndDependencyUse(object value, ServiceProviderDescription service, ITokenManager tokenManager, INonceStore nonceStore)
        {
            Contract.Requires(value != null);
            Contract.Requires(service != null);
            Contract.Requires(tokenManager != null);

            // In release builds, just quietly return.
            if (value == null || service == null || tokenManager == null)
            {
                return;
            }

            if (Enabled && Configuration.IncludeFeatureUsage)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(value.GetType().Name);
                builder.Append(" ");
                builder.Append(tokenManager.GetType().Name);
                if (nonceStore != null)
                {
                    builder.Append(" ");
                    builder.Append(nonceStore.GetType().Name);
                }
                builder.Append(" ");
                builder.Append(service.Version);
                builder.Append(" ");
                builder.Append(service.UserAuthorizationEndpoint);
                observedFeatures.Add(builder.ToString());
                Touch();
            }
        }
Exemplo n.º 10
0
        /// <summary>Initializes a new instance of the <see cref="OAuthCoordinator"/> class.</summary>
        /// <param name="consumerDescription">The description of the consumer.</param>
        /// <param name="serviceDescription">The service description that will be used to construct the Consumer and ServiceProvider objects.</param>
        /// <param name="consumerAction">The code path of the Consumer.</param>
        /// <param name="serviceProviderAction">The code path of the Service Provider.</param>
        internal OAuthCoordinator(ConsumerDescription consumerDescription, ServiceProviderDescription serviceDescription, Action <WebConsumer> consumerAction, Action <ServiceProvider> serviceProviderAction)
            : base(consumerAction, serviceProviderAction)
        {
            Requires.NotNull(consumerDescription, "consumerDescription");
            Requires.NotNull(serviceDescription, "serviceDescription");

            this.consumerDescription = consumerDescription;
            this.serviceDescription  = serviceDescription;
        }
Exemplo n.º 11
0
        /// <summary>Initializes a new instance of the <see cref="OAuthCoordinator"/> class.</summary>
        /// <param name="consumerDescription">The description of the consumer.</param>
        /// <param name="serviceDescription">The service description that will be used to construct the Consumer and ServiceProvider objects.</param>
        /// <param name="consumerAction">The code path of the Consumer.</param>
        /// <param name="serviceProviderAction">The code path of the Service Provider.</param>
        internal OAuthCoordinator(ConsumerDescription consumerDescription, ServiceProviderDescription serviceDescription, Action <WebConsumer> consumerAction, Action <ServiceProvider> serviceProviderAction)
            : base(consumerAction, serviceProviderAction)
        {
            Contract.Requires <ArgumentNullException>(consumerDescription != null);
            Contract.Requires <ArgumentNullException>(serviceDescription != null);

            this.consumerDescription = consumerDescription;
            this.serviceDescription  = serviceDescription;
        }
Exemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DesktopOAuthAuthorization"/> class.
        /// </summary>
        /// <param name="serviceDescription">The service description.</param>
        public DesktopOAuthAuthorization(ServiceProviderDescription serviceProviderDescription)
            : base(new DesktopConsumer(serviceProviderDescription, new WindowsCredentialStoreTokenManager()))
        {
            var inMemoryTokenManager = this.Consumer.TokenManager as WindowsCredentialStoreTokenManager;

            if (inMemoryTokenManager != null)
            {
                inMemoryTokenManager.SetAuthenticationTarget(this.AuthenticationTarget);
            }
        }
Exemplo n.º 13
0
        protected void identifierBox_LoggingIn(object sender, OpenIdEventArgs e)
        {
            ServiceProviderDescription serviceDescription = new ServiceProviderDescription {
                TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
            };

            var consumer = new WebConsumerOpenIdRelyingParty(serviceDescription, Global.OwnSampleOPHybridTokenManager);

            consumer.AttachAuthorizationRequest(e.Request, "http://tempuri.org/IDataApi/GetName");
        }
Exemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DotNetOpenAuthWebConsumer" /> class.
        /// </summary>
        /// <param name="serviceDescription">The service description.</param>
        /// <param name="consumerKey">The consumer key.</param>
        /// <param name="consumerSecret">The consumer secret.</param>
        public DotNetOpenAuthWebConsumer(ServiceProviderDescription serviceDescription, string consumerKey, string consumerSecret)
        {
            Requires.NotNull(serviceDescription, "serviceDescription");

            this.webConsumer = new Consumer {
                ServiceProvider            = serviceDescription,
                ConsumerKey                = consumerKey,
                ConsumerSecret             = consumerSecret,
                TemporaryCredentialStorage = new CookieTemporaryCredentialStorage(),
            };
        }
Exemplo n.º 15
0
        private void beginButton_Click(object sender, RoutedEventArgs e)
        {
            try {
                var service = new ServiceProviderDescription {
                    RequestTokenEndpoint      = new MessageReceivingEndpoint(this.requestTokenUrlBox.Text, this.requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
                    UserAuthorizationEndpoint = new MessageReceivingEndpoint(this.authorizeUrlBox.Text, HttpDeliveryMethods.GetRequest),
                    AccessTokenEndpoint       = new MessageReceivingEndpoint(this.accessTokenUrlBox.Text, this.accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
                    TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
                    ProtocolVersion           = this.oauthVersion.SelectedIndex == 0 ? ProtocolVersion.V10 : ProtocolVersion.V10a,
                };
                var tokenManager = new InMemoryTokenManager();
                tokenManager.ConsumerKey    = this.consumerKeyBox.Text;
                tokenManager.ConsumerSecret = this.consumerSecretBox.Text;

                var    consumer = new DesktopConsumer(service, tokenManager);
                string accessToken;
                if (service.ProtocolVersion == ProtocolVersion.V10)
                {
                    string requestToken;
                    Uri    authorizeUrl = consumer.RequestUserAuthorization(null, null, out requestToken);
                    Process.Start(authorizeUrl.AbsoluteUri);
                    MessageBox.Show(this, "Click OK when you've authorized the app.");
                    var authorizationResponse = consumer.ProcessUserAuthorization(requestToken, null);
                    accessToken = authorizationResponse.AccessToken;
                }
                else
                {
                    var authorizePopup = new Authorize(
                        consumer,
                        (DesktopConsumer c, out string requestToken) => c.RequestUserAuthorization(null, null, out requestToken));
                    authorizePopup.Owner = this;
                    bool?result = authorizePopup.ShowDialog();
                    if (result.HasValue && result.Value)
                    {
                        accessToken = authorizePopup.AccessToken;
                    }
                    else
                    {
                        return;
                    }
                }
                HttpDeliveryMethods resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest;
                if (this.resourceHttpMethodList.SelectedIndex == 1)
                {
                    resourceHttpMethod |= HttpDeliveryMethods.AuthorizationHeaderRequest;
                }
                var resourceEndpoint = new MessageReceivingEndpoint(this.resourceUrlBox.Text, resourceHttpMethod);
                using (IncomingWebResponse resourceResponse = consumer.PrepareAuthorizedRequestAndSend(resourceEndpoint, accessToken)) {
                    this.resultsBox.Text = resourceResponse.GetResponseReader().ReadToEnd();
                }
            } catch (DotNetOpenAuth.Messaging.ProtocolException ex) {
                MessageBox.Show(this, ex.Message);
            }
        }
Exemplo n.º 16
0
        private WebConsumer GetConsumer()
        {
            ServiceProviderDescription serviceDescription = new ServiceProviderDescription()
            {
                TamperProtectionElements = new DotNetOpenAuth.Messaging.ITamperProtectionChannelBindingElement[]
                {
                    new HmacSha1SigningBindingElement()
                }
            };

            return(new WebConsumer(serviceDescription, this._tokenManager));
        }
Exemplo n.º 17
0
        static TwitterCustomClient()
        {
            ServiceProviderDescription serviceProviderDescription = new ServiceProviderDescription();

            serviceProviderDescription.RequestTokenEndpoint      = new MessageReceivingEndpoint("https://api.twitter.com/oauth/request_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
            serviceProviderDescription.UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://api.twitter.com/oauth/authenticate", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
            serviceProviderDescription.AccessTokenEndpoint       = new MessageReceivingEndpoint("https://api.twitter.com/oauth/access_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
            serviceProviderDescription.TamperProtectionElements  = new ITamperProtectionChannelBindingElement[]
            {
                new HmacSha1SigningBindingElement()
            };
            TwitterCustomClient.TwitterServiceDescription = serviceProviderDescription;
        }
Exemplo n.º 18
0
        public void AccessTokenUriTest()
        {
            var target = new ServiceProviderDescription();
            MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/accesstoken", HttpDeliveryMethods.GetRequest);
            MessageReceivingEndpoint actual;

            target.AccessTokenEndpoint = expected;
            actual = target.AccessTokenEndpoint;
            Assert.AreEqual(expected, actual);

            target.AccessTokenEndpoint = null;
            Assert.IsNull(target.AccessTokenEndpoint);
        }
Exemplo n.º 19
0
     protected void Page_Load(object sender, EventArgs e)
     {
 // This is what the NetSuite SuiteSignOn ConnectionPoint sends:
 // GET /administratorportal/SSO/sso_page.aspx?oauth_token=08046c1c166a7a6c47471857502d364b0d59415418156f15db22f76dcfe648&dc=001&env=SANDBOX
 // see the NetSuite SuiteSignOn doc about dc & env processing to build endpoints
 ServiceProviderDescription provider = GetServiceDescription();
 
 // Set up OAuth with our keys and stuff
 string token = Request.Params["oauth_token"];
 string consumerKey = "yourconsumerkey";    // this has to match what is defined on our NetSuite account - ConnectionPoint to CRMLink
 string sharedSecret = "yoursharedsecret";        // this has to match what is defined on our NetSuite account - ConnectionPoint to CRMLink - Careful - NO funny chars like '!'
 
 // I got this InMemoryTokenManager from another DotNetOpenAuth post in SO
 InMemoryTokenManager _tokenManager = new InMemoryTokenManager(consumerKey, sharedSecret);
 AuthorizationApprovedResponse authApprovedResponse = new AuthorizationApprovedResponse();
 authApprovedResponse.RequestToken = token;
 
 _tokenManager.StoreOpenIdAuthorizedRequestToken(consumerKey, authApprovedResponse);
 
 WebConsumer consumer = new WebConsumer(provider, _tokenManager);
 
 // this is the SSO address in netsuite to use.  Should be production or sandbox, based on the values of dc and env
 string uri = "https://system.sandbox.netsuite.com/app/common/integration/ssoapplistener.nl";
                 MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint(uri, methods);
 
 WebRequest verifyRequest = consumer.PrepareAuthorizedRequest(endpoint, token );
 HttpWebResponse responseData = verifyRequest.GetResponse() as HttpWebResponse;
 
 XDocument responseXml;
 responseXml = XDocument.Load(responseData.GetResponseStream());
 
 // process the SSO values that come back from NetSuite in the XML  They should look something
 // like the following:
 /* XML response should look like this:
 
 <?xml version="1.0" encoding="UTF-8"?>
 <outboundSso>
     <entityInfo>
          <ENTITYINTERNALID>987654</ENTITYINTERNALID>
          <ENTITYNAME>Fred</ENTITYNAME>
          <ENTITYEMAIL>[email protected]</ENTITYEMAIL>
     </entityInfo>
 </outboundSso>
 */
 
 // If that data looks good, you can mark the user as logged in, and redirect to whatever
 // page (like SSOLandingPage.aspx) you want, which will be shown inside a frame on the NetSuite page.
 
 Response.Redirect("~/SSOLandingPage.aspx", false);
Exemplo n.º 20
0
        private WebConsumer GetConsumer()
        {
            MessageReceivingEndpoint   oauthEndpoint      = new MessageReceivingEndpoint(new Uri(this.AuthorisationUrl), HttpDeliveryMethods.PostRequest);
            ServiceProviderDescription serviceDescription = new ServiceProviderDescription()
            {
                RequestTokenEndpoint      = oauthEndpoint,
                UserAuthorizationEndpoint = oauthEndpoint,
                AccessTokenEndpoint       = oauthEndpoint,
                TamperProtectionElements  = new DotNetOpenAuth.Messaging.ITamperProtectionChannelBindingElement[]
                {
                    new HmacSha1SigningBindingElement()
                }
            };

            return(new WebConsumer(serviceDescription, this.TokenManager));
        }
Exemplo n.º 21
0
        public void SpecAppendixAExample()
        {
            ServiceProviderDescription serviceDescription = new ServiceProviderDescription()
            {
                RequestTokenEndpoint      = new MessageReceivingEndpoint("https://photos.example.net/request_token", HttpDeliveryMethods.PostRequest),
                UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://photos.example.net/authorize", HttpDeliveryMethods.GetRequest),
                AccessTokenEndpoint       = new MessageReceivingEndpoint("https://photos.example.net/access_token", HttpDeliveryMethods.PostRequest),
                TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] {
                    new PlaintextSigningBindingElement(),
                    new HmacSha1SigningBindingElement(),
                },
            };
            MessageReceivingEndpoint accessPhotoEndpoint = new MessageReceivingEndpoint("http://photos.example.net/photos?file=vacation.jpg&size=original", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest);
            ConsumerDescription      consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44");

            OAuthCoordinator coordinator = new OAuthCoordinator(
                consumerDescription,
                serviceDescription,
                consumer => {
                consumer.Channel.PrepareResponse(consumer.PrepareRequestUserAuthorization(new Uri("http://printer.example.com/request_token_ready"), null, null));                         // .Send() dropped because this is just a simulation
                string accessToken = consumer.ProcessUserAuthorization().AccessToken;
                var photoRequest   = consumer.CreateAuthorizingMessage(accessPhotoEndpoint, accessToken);
                OutgoingWebResponse protectedPhoto = ((CoordinatingOAuthChannel)consumer.Channel).RequestProtectedResource(photoRequest);
                Assert.IsNotNull(protectedPhoto);
                Assert.AreEqual(HttpStatusCode.OK, protectedPhoto.Status);
                Assert.AreEqual("image/jpeg", protectedPhoto.Headers[HttpResponseHeader.ContentType]);
                Assert.AreNotEqual(0, protectedPhoto.ResponseStream.Length);
            },
                sp => {
                var requestTokenMessage = sp.ReadTokenRequest();
                sp.Channel.PrepareResponse(sp.PrepareUnauthorizedTokenMessage(requestTokenMessage));                         // .Send() dropped because this is just a simulation
                var authRequest = sp.ReadAuthorizationRequest();
                ((InMemoryTokenManager)sp.TokenManager).AuthorizeRequestToken(authRequest.RequestToken);
                sp.Channel.PrepareResponse(sp.PrepareAuthorizationResponse(authRequest));                        // .Send() dropped because this is just a simulation
                var accessRequest = sp.ReadAccessTokenRequest();
                sp.Channel.PrepareResponse(sp.PrepareAccessTokenMessage(accessRequest));                         // .Send() dropped because this is just a simulation
                string accessToken = sp.ReadProtectedResourceAuthorization().AccessToken;
                ((CoordinatingOAuthChannel)sp.Channel).SendDirectRawResponse(new OutgoingWebResponse {
                    ResponseStream = new MemoryStream(new byte[] { 0x33, 0x66 }),
                    Headers        = new WebHeaderCollection {
                        { HttpResponseHeader.ContentType, "image/jpeg" },
                    },
                });
            });

            coordinator.Run();
        }
Exemplo n.º 22
0
        public static AuthorizedTokenResponse CompleteAuthorization(DesktopConsumer consumer, string requestToken, string userCode)
        {
            // Because Yammer has a proprietary callback_token parameter, and it's passed
            // with the message that specifically bans extra arguments being passed, we have
            // to cheat by adding the data to the URL itself here.
            var customServiceDescription = new ServiceProviderDescription {
                RequestTokenEndpoint      = ServiceDescription.RequestTokenEndpoint,
                UserAuthorizationEndpoint = ServiceDescription.UserAuthorizationEndpoint,
                AccessTokenEndpoint       = new MessageReceivingEndpoint(ServiceDescription.AccessTokenEndpoint.Location.AbsoluteUri + "?oauth_verifier=" + Uri.EscapeDataString(userCode), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest),
                TamperProtectionElements  = ServiceDescription.TamperProtectionElements,
                ProtocolVersion           = ProtocolVersion.V10,
            };

            // To use a custom service description we also must create a new WebConsumer.
            var customConsumer = new DesktopConsumer(customServiceDescription, consumer.TokenManager);
            var response       = customConsumer.ProcessUserAuthorization(requestToken, userCode);

            return(response);
        }
Exemplo n.º 23
0
    public static AuthorizedTokenResponse CompleteAuthorization(DesktopConsumer consumer, string requestToken, string userCode)
    {
        var customServiceDescription = new ServiceProviderDescription
        {
            RequestTokenEndpoint      = ServiceProviderDescription.RequestTokenEndpoint,
            UserAuthorizationEndpoint =
                new MessageReceivingEndpoint(
                    string.Format("{0}?key={1}&token={2}", ServiceProviderDescription.UserAuthorizationEndpoint.Location.AbsoluteUri,
                                  consumer.TokenManager.ConsumerKey, requestToken),
                    HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
            AccessTokenEndpoint = new MessageReceivingEndpoint(
                ServiceProviderDescription.AccessTokenEndpoint.Location.AbsoluteUri + "?oauth_verifier" + userCode + string.Empty,
                HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
            TamperProtectionElements = ServiceProviderDescription.TamperProtectionElements,
            ProtocolVersion          = ProtocolVersion.V10a
        };
        var customConsumer = new DesktopConsumer(customServiceDescription, consumer.TokenManager);
        var response       = customConsumer.ProcessUserAuthorization(requestToken, userCode);

        return(response);
    }
Exemplo n.º 24
0
        private async void beginButton_Click(object sender, RoutedEventArgs e)
        {
            try {
                var service = new ServiceProviderDescription(
                    this.requestTokenUrlBox.Text,
                    this.authorizeUrlBox.Text,
                    this.accessTokenUrlBox.Text);

                var consumer = new Consumer(this.consumerKeyBox.Text, this.consumerSecretBox.Text, service, new MemoryTemporaryCredentialStorage());
                DotNetOpenAuth.OAuth.AccessToken accessToken;
                var authorizePopup = new Authorize(consumer, c => c.RequestUserAuthorizationAsync(null, null));
                authorizePopup.Owner = this;
                bool?result = authorizePopup.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    accessToken = authorizePopup.AccessToken;
                }
                else
                {
                    return;
                }

                HttpMethod resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpMethod.Get : HttpMethod.Post;
                using (var handler = consumer.CreateMessageHandler(accessToken)) {
                    handler.Location = this.resourceHttpMethodList.SelectedIndex == 1
                                                                                   ? OAuth1HttpMessageHandlerBase.OAuthParametersLocation.AuthorizationHttpHeader
                                                                                   : OAuth1HttpMessageHandlerBase.OAuthParametersLocation.QueryString;
                    using (var httpClient = consumer.CreateHttpClient(handler)) {
                        var request = new HttpRequestMessage(resourceHttpMethod, this.resourceUrlBox.Text);
                        using (var resourceResponse = await httpClient.SendAsync(request)) {
                            this.resultsBox.Text = await resourceResponse.Content.ReadAsStringAsync();
                        }
                    }
                }
            } catch (DotNetOpenAuth.Messaging.ProtocolException ex) {
                MessageBox.Show(this, ex.Message);
            }
        }
Exemplo n.º 25
0
        public async Task SpecAppendixAExample()
        {
            var serviceDescription = new ServiceProviderDescription(
                "https://photos.example.net/request_token",
                "http://photos.example.net/authorize",
                "https://photos.example.net/access_token");
            var serviceHostDescription = new ServiceProviderHostDescription {
                RequestTokenEndpoint      = new MessageReceivingEndpoint(serviceDescription.TemporaryCredentialsRequestEndpoint, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
                UserAuthorizationEndpoint = new MessageReceivingEndpoint(serviceDescription.ResourceOwnerAuthorizationEndpoint, HttpDeliveryMethods.GetRequest),
                AccessTokenEndpoint       = new MessageReceivingEndpoint(serviceDescription.TokenRequestEndpoint, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
                TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement(), },
            };
            var accessPhotoEndpoint = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original");
            var consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44");

            var tokenManager = new InMemoryTokenManager();

            tokenManager.AddConsumer(consumerDescription);
            var sp = new ServiceProvider(serviceHostDescription, tokenManager);

            Handle(serviceDescription.TemporaryCredentialsRequestEndpoint).By(
                async(request, ct) => {
                var requestTokenMessage = await sp.ReadTokenRequestAsync(request, ct);
                return(await sp.Channel.PrepareResponseAsync(sp.PrepareUnauthorizedTokenMessage(requestTokenMessage)));
            });
            Handle(serviceDescription.ResourceOwnerAuthorizationEndpoint).By(
                async(request, ct) => {
                var authRequest = await sp.ReadAuthorizationRequestAsync(request, ct);
                ((InMemoryTokenManager)sp.TokenManager).AuthorizeRequestToken(authRequest.RequestToken);
                return(await sp.Channel.PrepareResponseAsync(sp.PrepareAuthorizationResponse(authRequest)));
            });
            Handle(serviceDescription.TokenRequestEndpoint).By(
                async(request, ct) => {
                var accessRequest = await sp.ReadAccessTokenRequestAsync(request, ct);
                return(await sp.Channel.PrepareResponseAsync(sp.PrepareAccessTokenMessage(accessRequest), ct));
            });
            Handle(accessPhotoEndpoint).By(
                async(request, ct) => {
                string accessToken = (await sp.ReadProtectedResourceAuthorizationAsync(request)).AccessToken;
                Assert.That(accessToken, Is.Not.Null.And.Not.Empty);
                var responseMessage = new HttpResponseMessage {
                    Content = new ByteArrayContent(new byte[] { 0x33, 0x66 }),
                };
                responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                return(responseMessage);
            });

            var consumer = new Consumer(
                consumerDescription.ConsumerKey,
                consumerDescription.ConsumerSecret,
                serviceDescription,
                new MemoryTemporaryCredentialStorage());

            consumer.HostFactories = this.HostFactories;
            var authorizeUrl = await consumer.RequestUserAuthorizationAsync(new Uri("http://printer.example.com/request_token_ready"));

            Uri authorizeResponseUri;

            this.HostFactories.AllowAutoRedirects = false;
            using (var httpClient = this.HostFactories.CreateHttpClient()) {
                using (var response = await httpClient.GetAsync(authorizeUrl)) {
                    Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redirect));
                    authorizeResponseUri = response.Headers.Location;
                }
            }

            var accessTokenResponse = await consumer.ProcessUserAuthorizationAsync(authorizeResponseUri);

            Assert.That(accessTokenResponse, Is.Not.Null);

            using (var authorizingClient = consumer.CreateHttpClient(accessTokenResponse.AccessToken)) {
                using (var protectedPhoto = await authorizingClient.GetAsync(accessPhotoEndpoint)) {
                    Assert.That(protectedPhoto, Is.Not.Null);
                    protectedPhoto.EnsureSuccessStatusCode();
                    Assert.That("image/jpeg", Is.EqualTo(protectedPhoto.Content.Headers.ContentType.MediaType));
                    Assert.That(protectedPhoto.Content.Headers.ContentLength, Is.Not.EqualTo(0));
                }
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WebOAuthAuthorization"/> class.
 /// </summary>
 /// <param name="serviceProviderDescription">The service provider description.</param>
 public MvcOAuthAuthorization(IConsumerTokenManager tokenManager, string accessToken, ServiceProviderDescription serviceProviderDescription) :
     base(tokenManager, accessToken, serviceProviderDescription)
 {
 }
Exemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DesktopOAuthAuthorization"/> class
 /// that uses a custom token manager.
 /// </summary>
 /// <param name="tokenManager">The token manager.</param>
 /// <param name="accessToken">The access token.</param>
 public DesktopOAuthAuthorization(IConsumerTokenManager tokenManager, string accessToken, ServiceProviderDescription serviceProviderDescription)
     : base(new DesktopConsumer(serviceProviderDescription, tokenManager))
 {
     this.accessToken = accessToken;
 }
Exemplo n.º 28
0
        public void RequestTokenUriWithOAuthParametersTest()
        {
            var target = new ServiceProviderDescription();

            target.RequestTokenEndpoint = new MessageReceivingEndpoint("http://localhost/requesttoken?oauth_token=something", HttpDeliveryMethods.GetRequest);
        }
Exemplo n.º 29
0
        private static HttpMessageHandler OAuthHandler(string requestTokenURL,
                                                       string authorizationTokenURL,
                                                       string accessTokenURL,
                                                       string consumerKey,
                                                       string consumerSecret,
                                                       string user,
                                                       string passwd,
                                                       string authUrl)
        {
            ServiceProviderDescription serviceDescription = new ServiceProviderDescription();

            serviceDescription.AccessTokenEndpoint       = new MessageReceivingEndpoint(new Uri(accessTokenURL), HttpDeliveryMethods.PostRequest);
            serviceDescription.ProtocolVersion           = ProtocolVersion.V10a;
            serviceDescription.RequestTokenEndpoint      = new MessageReceivingEndpoint(new Uri(requestTokenURL), HttpDeliveryMethods.PostRequest);
            serviceDescription.TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() };
            serviceDescription.UserAuthorizationEndpoint = new MessageReceivingEndpoint(new Uri(authorizationTokenURL), HttpDeliveryMethods.PostRequest);

            TokenManager tokenManager = new TokenManager(consumerKey, consumerSecret);
            WebConsumer  consumer     = new WebConsumer(serviceDescription, tokenManager);

            // callback is never called by CLM, but needed to do OAuth based forms login
            // XXX - Dns.GetHostName() alway seems to return simple, uppercased hostname
            string callback = "https://" + Dns.GetHostName() + '.' + IPGlobalProperties.GetIPGlobalProperties().DomainName + ":9443/cb";

            callback = callback.ToLower();

            consumer.PrepareRequestUserAuthorization(new Uri(callback), null, null);
            OslcClient oslcClient = new OslcClient();
            HttpClient client     = oslcClient.GetHttpClient();

            HttpStatusCode      statusCode = HttpStatusCode.Unused;
            string              location   = null;
            HttpResponseMessage resp;

            try
            {
                client.DefaultRequestHeaders.Clear();

                resp = client.GetAsync(authorizationTokenURL + "?oauth_token=" + tokenManager.GetRequestToken() +
                                       "&oauth_callback=" + Uri.EscapeUriString(callback).Replace("#", "%23").Replace("/", "%2F").Replace(":", "%3A")).Result;
                statusCode = resp.StatusCode;

                if (statusCode == HttpStatusCode.Found)
                {
                    location = resp.Headers.Location.AbsoluteUri;
                    resp.ConsumeContent();
                    statusCode = FollowRedirects(client, statusCode, location);
                }

                string        securityCheckUrl = "j_username="******"&j_password="******"application/x-www-form-urlencoded");

                mediaTypeValue.CharSet = "utf-8";

                content.Headers.ContentType = mediaTypeValue;

                resp       = client.PostAsync(authUrl + "/j_security_check", content).Result;
                statusCode = resp.StatusCode;

                string jazzAuthMessage      = null;
                IEnumerable <string> values = new List <string>();

                if (resp.Headers.TryGetValues(JAZZ_AUTH_MESSAGE_HEADER, out values))
                {
                    jazzAuthMessage = values.Last();
                }

                if (jazzAuthMessage != null && string.Compare(jazzAuthMessage, JAZZ_AUTH_FAILED, true) == 0)
                {
                    resp.ConsumeContent();
                    throw new JazzAuthFailedException(user, authUrl);
                }
                else if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Found)
                {
                    resp.ConsumeContent();
                    throw new JazzAuthErrorException(statusCode, authUrl);
                }
                else         //success
                {
                    Uri callbackUrl = resp.Headers.Location;

                    resp        = client.GetAsync(callbackUrl.AbsoluteUri).Result;
                    callbackUrl = resp.Headers.Location;
                    resp        = client.GetAsync(callbackUrl.AbsoluteUri).Result;
                    callbackUrl = resp.Headers.Location;

                    NameValueCollection qscoll = callbackUrl.ParseQueryString();

                    if (callbackUrl.OriginalString.StartsWith(callback + '?') && qscoll["oauth_verifier"] != null)
                    {
                        DesktopConsumer         desktopConsumer         = new DesktopConsumer(serviceDescription, tokenManager);
                        AuthorizedTokenResponse authorizedTokenResponse = desktopConsumer.ProcessUserAuthorization(tokenManager.GetRequestToken(), qscoll["oauth_verifier"]);

                        return(consumer.CreateAuthorizingHandler(authorizedTokenResponse.AccessToken, CreateSSLHandler()));
                    }

                    throw new JazzAuthErrorException(statusCode, authUrl);
                }
            } catch (JazzAuthFailedException jfe) {
                throw jfe;
            } catch (JazzAuthErrorException jee) {
                throw jee;
            } catch (Exception e) {
                Console.WriteLine(e.StackTrace);
            }

            // return consumer.CreateAuthorizingHandler(accessToken);
            return(null);
        }
Exemplo n.º 30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuthClient" /> class.
 /// </summary>
 /// <param name="providerName">Name of the provider.</param>
 /// <param name="serviceDescription">The service Description.</param>
 /// <param name="consumerKey">The consumer key.</param>
 /// <param name="consumerSecret">The consumer secret.</param>
 protected OAuthClient(
     string providerName, ServiceProviderDescription serviceDescription, string consumerKey, string consumerSecret)
     : this(providerName, new DotNetOpenAuthWebConsumer(serviceDescription, consumerKey, consumerSecret))
 {
 }