Exemplo n.º 1
0
        /// <summary>
        /// Begins the Linked In OAuth process
        /// </summary>
        /// <param name="procParams"></param>
        /// <returns></returns>
        public GeneralSuccessResultViewModel Execute(StartLinkedInUserAuthParams procParams)
        {
            var consumer = new WebConsumer(GetLiDescription(), new LinkedInTokenManager(_context, procParams.RequestingUserId));

            consumer.Channel.Send(consumer.PrepareRequestUserAuthorization(procParams.ReturnUrl, null, null));
            return(new GeneralSuccessResultViewModel());
        }
Exemplo n.º 2
0
 public JohnDeereClient(HttpContextBase context, string baseAddress, string consumerKey, string consumerSecret)
 {
     _BaseAddress  = baseAddress;
     _Context      = context;
     _TokenManager = new SimpleConsumerTokenManager(consumerKey, consumerSecret, new CookieOAuthTokenManager(context));
     _WebWorker    = new WebConsumer(ServiceDescription, _TokenManager);
 }
Exemplo n.º 3
0
    protected void downloadUpdates_Click(object sender, EventArgs e)
    {
        var            twitter       = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager);
        XPathDocument  updates       = new XPathDocument(TwitterConsumer.GetUpdates(twitter, this.AccessToken).CreateReader());
        XPathNavigator nav           = updates.CreateNavigator();
        var            parsedUpdates = from status in nav.Select("/statuses/status").OfType <XPathNavigator>()
                                       where !status.SelectSingleNode("user/protected").ValueAsBoolean
                                       select new {
            User   = status.SelectSingleNode("user/name").InnerXml,
            Status = status.SelectSingleNode("text").InnerXml,
        };

        StringBuilder tableBuilder = new StringBuilder();

        tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>");

        foreach (var update in parsedUpdates)
        {
            tableBuilder.AppendFormat(
                "<tr><td>{0}</td><td>{1}</td></tr>",
                HttpUtility.HtmlEncode(update.User),
                HttpUtility.HtmlEncode(update.Status));
        }
        tableBuilder.Append("</table>");
        resultsPlaceholder.Controls.Add(new Literal {
            Text = tableBuilder.ToString()
        });
    }
        public static JArray GetUserTimeLine(WebConsumer consumer, String accessToken, int userId, String screenName, bool includeRetweets, int count)
        {
            var parameters = new Dictionary <String, string>();

            parameters.Add("count", count.ToString(CultureInfo.InvariantCulture));
            parameters.Add("include_rts", includeRetweets.ToString());

            if (!String.IsNullOrEmpty(screenName))
            {
                parameters.Add("screen_name", screenName);
            }

            if (userId > 0)
            {
                parameters.Add("user_id", userId.ToString(CultureInfo.InvariantCulture));
            }

            HttpWebRequest      request  = consumer.PrepareAuthorizedRequest(GetUserTimeLineEndPoint, accessToken, parameters);
            IncomingWebResponse response = consumer.Channel.WebRequestHandler.GetResponse(request);

            using (var responseReader = response.GetResponseReader())
            {
                var result = responseReader.ReadToEnd();

                return(JArray.Parse(result));
            }
        }
Exemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //Аутентифицируемся при загрузке странички
                if (!IsPostBack)
                {
                    var yahoo = new WebConsumer(YahooConsumer.ServiceDescription, this.TokenManager);

                    // Is Google calling back with authorization?
                    var accessTokenResponse = yahoo.ProcessUserAuthorization();
                    if (accessTokenResponse != null)
                    {
                        AccessToken = accessTokenResponse.AccessToken;
                        YahooGuid   = accessTokenResponse.ExtraData["xoauth_yahoo_guid"];
                        //Redirecting to result page
                        Response.Redirect("YahooAddressBook.aspx");
                    }
                    // If we don't yet have access, immediately request it.
                    YahooConsumer.RequestAuthorization(yahoo);
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                SubmitError(ex.Message);
            }
        }
Exemplo n.º 6
0
        public ActionResult OpenIdTwitter()
        {
            var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager);
            // Is Twitter calling back with authorization?
            var accessTokenResponse = twitter.ProcessUserAuthorization();

            if (accessTokenResponse != null)
            {
                this.AccessToken = accessTokenResponse.AccessToken;
                FormsAuthentication.SetAuthCookie("<em>user_id</em>", true);
                SetUserIdentityForView(accessTokenResponse.ExtraData["user_id"]);
                createUserIfNotExist(accessTokenResponse.ExtraData["user_id"], accessTokenResponse.ExtraData["screen_name"].ToString());
            }
            else if (this.AccessToken == null)
            {
                // If we don't yet have access, immediately request it.
                twitter.Channel.Send(twitter.PrepareRequestUserAuthorization());
            }
            string returnUrl = Request.Form["returnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                return(Redirect(returnUrl));
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
            // If we're to this point, login didn't complete successfully.
            // Show the LogOn view again to show the user any errors and
            // give another chance to complete login.
            return(View("LogOn"));
        }
Exemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //get the values from authHandler and service (or the scope which will be accessed)
                if (Session["authHandler"] != null)
                {
                    authHandleTextBox.Text = (String)Session["authHandler"];
                }

                if (Session["serviceScope"] != null)
                {
                    serviceTextBox.Text = (String)Session["serviceScope"];
                }

                if (Session["WcfTokenManager"] != null)
                {
                    WebConsumer consumer           = this.CreateConsumer();
                    var         accessTokenMessage = consumer.ProcessUserAuthorization();
                    if (accessTokenMessage != null)
                    {
                        Session["WcfAccessToken"]    = accessTokenMessage.AccessToken;
                        this.authorizationLabel.Text = "Authorized!  Access token: " + accessTokenMessage.AccessToken;
                    }
                }
            }
        }
Exemplo n.º 8
0
        public string GetTweets()
        {
            // Uppgift 6:
            var            twitter       = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager);
            XPathDocument  updates       = new XPathDocument(TwitterConsumer.GetUpdates(twitter, this.AccessToken).CreateReader());
            XPathNavigator nav           = updates.CreateNavigator();
            var            parsedUpdates = from status in nav.Select("/statuses/status").OfType <XPathNavigator>()
                                           where !status.SelectSingleNode("user/protected").ValueAsBoolean
                                           select new
            {
                User   = status.SelectSingleNode("user/name").InnerXml,
                Status = status.SelectSingleNode("text").InnerXml,
            };

            StringBuilder tableBuilder = new StringBuilder();

            tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>");

            foreach (var update in parsedUpdates)
            {
                tableBuilder.AppendFormat(
                    "<tr><td>{0}</td><td>{1}</td></tr>",
                    HttpUtility.HtmlEncode(update.User),
                    HttpUtility.HtmlEncode(update.Status));
            }
            tableBuilder.Append("</table>");
            return(tableBuilder.ToString());
        }
Exemplo n.º 9
0
    private WebConsumer CreateConsumer()
    {
        string consumerKey    = "sampleconsumer";
        string consumerSecret = "samplesecret";
        var    tokenManager   = Session["WcfTokenManager"] as InMemoryTokenManager;

        if (tokenManager == null)
        {
            tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret);
            Session["WcfTokenManager"] = tokenManager;
        }
        MessageReceivingEndpoint oauthEndpoint = new MessageReceivingEndpoint(
            new Uri("http://localhost:65169/OAuthServiceProvider/OAuth.ashx"),
            HttpDeliveryMethods.PostRequest);
        WebConsumer consumer = new WebConsumer(
            new ServiceProviderDescription {
            RequestTokenEndpoint      = oauthEndpoint,
            UserAuthorizationEndpoint = oauthEndpoint,
            AccessTokenEndpoint       = oauthEndpoint,
            TamperProtectionElements  = new DotNetOpenAuth.Messaging.ITamperProtectionChannelBindingElement[] {
                new HmacSha1SigningBindingElement(),
            },
        },
            tokenManager);

        return(consumer);
    }
Exemplo n.º 10
0
        public void BeginAuthentication()
        {
            WebConsumer consumer = this.GetConsumer();

            UriBuilder callback = new UriBuilder(HttpContext.Current.Request.Url);

            callback.Query = null;
            string[] scopes        = new string[0];
            string   scope         = string.Join("|", scopes);
            var      requestParams = new Dictionary <string, string> {
                { "scope", scope },
            };

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

            if (!string.IsNullOrWhiteSpace(this.ReferrerCode))
            {
                redirectParams[MiiCardConsumer.OAUTH_PARAM_REFERRER_CODE] = this.ReferrerCode;
            }

            if (this.ForceClaimsPicker)
            {
                redirectParams[MiiCardConsumer.OAUTH_PARAM_FORCE_CLAIMS_PICKER] = true.ToString();
            }

            if (redirectParams.Count == 0)
            {
                redirectParams = null;
            }

            var request = consumer.PrepareRequestUserAuthorization(callback.Uri, requestParams, redirectParams);

            consumer.Channel.Send(request);
        }
Exemplo n.º 11
0
        public static JObject GetUserInfo(WebConsumer consumer, int userid, String screenName, string accessToken)
        {
            var    baseUri = "https://api.twitter.com/1.1/users/show.json";
            String uri     = String.Empty;

            if (userid > 0 && String.IsNullOrEmpty(screenName))
            {
                uri = String.Concat(baseUri, "?user_id=", userid);
            }

            if (userid == 0 && !String.IsNullOrEmpty(screenName))
            {
                uri = String.Concat(baseUri, "?screen_name=", screenName);
            }

            var endpoint = new MessageReceivingEndpoint(uri, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
            IncomingWebResponse response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken);

            using (var responseReader = response.GetResponseReader())
            {
                var result = responseReader.ReadToEnd();

                return(JObject.Parse(result));
            }
        }
Exemplo n.º 12
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.º 14
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() },
            };
            WebConsumer consumer = new WebConsumer(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.º 15
0
        private WebConsumer CreateConsumer()
        {
            String authHandler    = authHandleTextBox.Text;
            string consumerKey    = consumerKeyTextBox.Text;
            string consumerSecret = consumerSecretTextBox.Text;

            Session["authHandler"] = authHandler;

            var tokenManager = Session["WcfTokenManager"] as InMemoryTokenManager;

            if (tokenManager == null)
            {
                tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret);
                Session["WcfTokenManager"] = tokenManager;
            }
            MessageReceivingEndpoint oauthEndpoint = new MessageReceivingEndpoint(
                new Uri(authHandler),
                HttpDeliveryMethods.PostRequest);
            WebConsumer consumer = new WebConsumer(
                new ServiceProviderDescription
            {
                RequestTokenEndpoint      = oauthEndpoint,
                UserAuthorizationEndpoint = oauthEndpoint,
                AccessTokenEndpoint       = oauthEndpoint,
                TamperProtectionElements  = new DotNetOpenAuth.Messaging.ITamperProtectionChannelBindingElement[] {
                    new HmacSha1SigningBindingElement(),
                },
            },
                tokenManager);

            return(consumer);
        }
Exemplo n.º 16
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);
        }
        public HttpWebRequest EditDocument(string documentId, string projectCode, int projectId, int issueId)
        {
            InMemoryTokenManager t = GetTokenManager(_user);

            var lucid = new WebConsumer(ServiceDescription, t);

            return(lucid.PrepareAuthorizedRequest(new MessageReceivingEndpoint(string.Format(lucidBaseChartUrl + "documents/edit/{0}?callback={4}apps/lucidchart/editdocument/{1}/{2}/{3}", documentId, projectCode, projectId, issueId, _geminiUrl), HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), _user.Token));
        }
Exemplo n.º 18
0
            public Investigator()
            {
                logger = LogManager.GetLogger(typeof(Investigator));
                InMemoryTokenManager tokenManager = new InMemoryTokenManager(Constants.TwitterConsumerKey, Constants.TwitterConsumerSecret);

                tokenManager.StoreAccessToken(Constants.TwitterAccessToken, Constants.TwitterAccessSecret);
                consumer = new WebConsumer(UserModule.ServiceDescription, tokenManager);
            }
Exemplo n.º 19
0
        public static XDocument GetUserInfo(WebConsumer consumer, int userid, string accessToken)
        {
            var endpoint = new MessageReceivingEndpoint("http://api.twitter.com/1/users/show.xml?user_id=" + userid, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
            IncomingWebResponse response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken);
            var doc = XDocument.Load(XmlReader.Create(response.GetResponseReader()));

            return(doc);
        }
Exemplo n.º 20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var    google      = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager);
            string accessToken = google.RequestNewClientAccount();
            ////string tokenSecret = google.TokenManager.GetTokenSecret(accessToken);
            MessageReceivingEndpoint ep = null;             // set up your authorized call here.

            google.PrepareAuthorizedRequestAndSend(ep, accessToken);
        }
        public LucidDocument GetDocumentDescription(string documentId)
        {
            InMemoryTokenManager t = GetTokenManager(_user);

            var lucid = new WebConsumer(ServiceDescription, t);

            string url = lucidBaseChartUrl + "documents/describe/" + documentId;

            HttpWebRequest req = lucid.PrepareAuthorizedRequest(new MessageReceivingEndpoint(url, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), _user.Token);

            req.ContentType = "application/xml";

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

            string xml = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd();

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xml);

            LucidDocument document = new LucidDocument();

            XmlElement elm = doc.DocumentElement;

            foreach (XmlElement n in elm.ChildNodes[0])
            {
                switch (n.Name.ToLower())
                {
                case "documentid":
                    document.Id = n.InnerText;
                    break;

                case "title":
                    document.Name = n.InnerText;
                    break;

                case "editurl":
                    document.EditUrl = n.InnerText;
                    break;

                case "viewurl":
                    document.ViewUrl = n.InnerText;
                    break;

                case "version":
                    document.Version = n.InnerText;
                    break;

                case "pagecount":
                    document.PageCount = n.InnerText.ToInt();
                    break;
                }
            }

            return(document);
        }
        public TwitterProxy(IConsumerTokenManager manager, ISignInEndpointBuilder endpointBuilder,
                            IFubuRequest request, ISystemUrls urls)
        {
            _request = request;
            _urls    = urls;

            var endpoints = endpointBuilder.Build();

            _consumer = new WebConsumer(endpoints, manager);
        }
Exemplo n.º 23
0
        protected void identifierBox_LoggingIn(object sender, OpenIdEventArgs e)
        {
            ServiceProviderDescription serviceDescription = new ServiceProviderDescription {
                TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
            };

            WebConsumer consumer = new WebConsumer(serviceDescription, Global.OwnSampleOPHybridTokenManager);

            consumer.AttachAuthorizationRequest(e.Request, "http://tempuri.org/IDataApi/GetName");
        }
Exemplo n.º 24
0
        //http://api.linkedin.com/v1/people/~
        public static void RequestAuthorization(WebConsumer consumer)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException("consumer");
            }
            Uri callback = Util.GetCallbackUrlFromContext().StripQueryArgumentsWithPrefix("oauth_");
            var request  = consumer.PrepareRequestUserAuthorization(callback, null, null);

            consumer.Channel.Send(request);
        }
Exemplo n.º 25
0
        public void StartAuthentication(Uri callBackUrl)
        {
            var request = HttpContext.Current.Request;

            using (var twitter = new WebConsumer(ServiceDescription, _tokenManager))
            {
                twitter.Channel.Send(
                    twitter.PrepareRequestUserAuthorization(callBackUrl, null, null)
                    );
            }
        }
Exemplo n.º 26
0
        //http://api.linkedin.com/v1/people/~
        public static void RequestAuthorization(WebConsumer consumer)
        {
            if (consumer == null)
            {
                throw new ArgumentNullException("consumer");
            }
            Uri callback = HttpRequestExtensions.GetUrlRewriter(HttpContext.Current.Request.Headers, Util.GetCallbackUrlFromContext().StripQueryArgumentsWithPrefix("oauth_"));
            var request  = consumer.PrepareRequestUserAuthorization(callback, null, null);

            consumer.Channel.Send(request);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Prepares a redirect that will send the user to Twitter to sign in.
        /// </summary>
        /// <param name="forceNewLogin">if set to <c>true</c> the user will be required to re-enter their Twitter credentials even if already logged in to Twitter.</param>
        /// <returns>The redirect message.</returns>
        /// <remarks>
        /// Call <see cref="OutgoingWebResponse.Send"/> or
        /// <c>return StartSignInWithTwitter().<see cref="MessagingUtilities.AsActionResult">AsActionResult()</see></c>
        /// to actually perform the redirect.
        /// </remarks>
        public static OutgoingWebResponse StartSignInWithTwitter(WebConsumer consumer, bool forceNewLogin)
        {
            var redirectParameters = new Dictionary <string, string>();

            if (forceNewLogin)
            {
                redirectParameters["force_login"] = "******";
            }
            Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix("oauth_");
            var request  = consumer.PrepareRequestUserAuthorization(callback, null, redirectParameters);

            return(consumer.Channel.PrepareResponse(request));
        }
Exemplo n.º 28
0
        public static JArray SearchUsers(WebConsumer consumer, String search, string accessToken)
        {
            var endpoint = new MessageReceivingEndpoint("https://api.twitter.com/1.1/users/search.json?q=" + search, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);

            IncomingWebResponse response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken);

            using (var responseReader = response.GetResponseReader())
            {
                var result = responseReader.ReadToEnd();

                return(JArray.Parse(result));
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Checks the incoming web request to see if it carries a Twitter authentication response,
        /// and provides the user's Twitter screen name and unique id if available.
        /// </summary>
        /// <param name="screenName">The user's Twitter screen name.</param>
        /// <param name="userId">The user's Twitter unique user ID.</param>
        /// <returns>
        /// A value indicating whether Twitter authentication was successful;
        /// otherwise <c>false</c> to indicate that no Twitter response was present.
        /// </returns>
        public bool CompleteAuthenticate()
        {
            using (WebConsumer consumer = new WebConsumer(SignInWithTwitterServiceDescription, this.Consumer.TokenManager))
            {
                var response = consumer.ProcessUserAuthorization();
                if (response == null)
                {
                    return(false);
                }

                this.ParseUserInfoFromAuthorizationResult(response.ExtraData);
                return(true);
            }
        }
Exemplo n.º 30
0
        protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
        {
            var    profileEndpoint = new MessageReceivingEndpoint("https://publicapi.avans.nl/oauth/studentnummer/?format=json", HttpDeliveryMethods.GetRequest);
            string accessToken     = response.AccessToken;

            consumerKey    = ConfigurationManager.AppSettings["AvansOAuthConsumerKey"];
            consumerSecret = ConfigurationManager.AppSettings["AvansOAuthConsumerSecret"];
            InMemoryOAuthTokenManager tokenManager = new InMemoryOAuthTokenManager(consumerKey, consumerSecret);

            tokenManager.ExpireRequestTokenAndStoreNewAccessToken(String.Empty, String.Empty, accessToken, (response as ITokenSecretContainingMessage).TokenSecret);
            WebConsumer webConsumer = new WebConsumer(AvansServiceDescription, tokenManager);

            HttpWebRequest request = webConsumer.PrepareAuthorizedRequest(profileEndpoint, accessToken);

            try
            {
                using (WebResponse profileResponse = request.GetResponse())
                {
                    using (Stream profileResponseStream = profileResponse.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(profileResponseStream))
                        {
                            string jsonText = reader.ReadToEnd();

                            var user = JsonConvert.DeserializeObject <List <OAuthUser> >(jsonText);

                            Dictionary <string, string> extraData = new Dictionary <string, string>();
                            extraData.Add("Id", user[0].Studentnummer ?? "Onbekend");
                            extraData.Add("Login", user[0].Inlognaam ?? "Onbekend");

                            DatabaseFactory.getInstance().getDAOStudent().putStudentInDatabase(Convert.ToInt32(user[0].Studentnummer), user[0].Inlognaam);

                            return(new DotNetOpenAuth.AspNet.AuthenticationResult(true, ProviderName, extraData["Id"], extraData["Login"], extraData));
                        }
                    }
                }
                return(new AuthenticationResult(false));
            }
            catch (WebException ex)
            {
                using (Stream s = ex.Response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(s))
                    {
                        string body = sr.ReadToEnd();
                        return(new DotNetOpenAuth.AspNet.AuthenticationResult(new Exception(body, ex)));
                    }
                }
            }
        }