Beispiel #1
0
        private async Task <DialogTurnResult> CorreosStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog.
            // Running a prompt here means the next WaterfallStep will be run when the users response is received.

            // return await stepContext.PromptAsync("name", new PromptOptions { Prompt = MessageFactory.Text("Please enter your name.") }, cancellationToken);



            try
            {
                var tokenResponse = (TokenResponse)stepContext.Result;
                if (tokenResponse != null)
                {
                    //throw new InvalidOperationException("xd1");
                    await OAuthHelpers.ListRecentMailAsync(stepContext.Context, stepContext.Result as TokenResponse);

                    return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
                }
                else
                {
                    //List.
                    //throw new InvalidOperationException("xd");
                    return(await stepContext.ReplaceDialogAsync(this.Id, null, cancellationToken));
                }
            }
            catch (Exception error)
            {
                //accessors.UserProfile.Name
                return(await stepContext.ReplaceDialogAsync(this.Id, null, cancellationToken));

                throw new InvalidOperationException(error.Message + stepContext.Result);
                //return await stepContext.ReplaceDialogAsync(this.Id, null, cancellationToken);
            }
        }
        private async Task <DialogTurnResult> ProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var rawValues   = (JObject)stepContext.Context.Activity.Value;
            var userProfile = (UserProfile)stepContext.Values[UserInfo];

            userProfile.Domain            = (string)rawValues.GetValue("Domain");
            userProfile.UserPrincipalName = userProfile.DomainName + userProfile.Domain;

            Dictionary <string, object> args = (Dictionary <string, object>)stepContext.Options;

            string        topScoringIntent = (string)args["topScoringIntent"];
            TokenResponse tokenResponse    = (TokenResponse)args["TokenResponse"];


            if (topScoringIntent == "Get User")
            {
                Attachment cardAttachment = (Attachment)args["cardAttachment"];
                await OAuthHelpers.GetUserAsync(stepContext.Context, tokenResponse, userProfile.UserPrincipalName);
            }
            else if (topScoringIntent == "Disable User")
            {
                await OAuthHelpers.DisableUserAsync(stepContext.Context, tokenResponse, userProfile.UserPrincipalName);
            }
            else if (topScoringIntent == "Enable User")
            {
                await OAuthHelpers.EnableUserAsync(stepContext.Context, tokenResponse, userProfile.UserPrincipalName);
            }

            return(await stepContext.EndDialogAsync(null, cancellationToken));
        }
Beispiel #3
0
        private async Task <DialogTurnResult> PromptStepAsync(WaterfallStepContext step, CancellationToken cancellationToken)
        {
            var activity = step.Context.Activity;

            if (step.Result.ToString() == "Ver ultimos correos")
            {
                await OAuthHelpers.ListRecentMailAsync(step.Context, step.Result as TokenResponse);
            }
            else if (step.Result.ToString() == "Otro")
            {
                var reply = step.Context.Activity.CreateReply();
                reply.Attachments = new List <Attachment> {
                    CreateHeroCard().ToAttachment()
                };
                reply.Text = "Ingresa la consulta";
                return(await step.BeginDialogAsync("waterfallStepsOtro", cancellationToken : cancellationToken));

                //await step.Context.SendActivityAsync(reply, cancellationToken);
            }
            // Set the context if the message is not the magic code.
            if (activity.Type == ActivityTypes.Message && !Regex.IsMatch(activity.Text, @"(\d{6})"))
            {
                await accessors.CommandState.SetAsync(step.Context, activity.Text, cancellationToken);

                await accessors.UserState.SaveChangesAsync(step.Context, cancellationToken : cancellationToken);
            }

            return(await step.BeginDialogAsync("loginPrompt", cancellationToken : cancellationToken));
        }
Beispiel #4
0
        private async Task <DialogTurnResult> ProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            Dictionary <string, object> args = (Dictionary <string, object>)stepContext.Options;
            TokenResponse tokenResponse      = (TokenResponse)args["TokenResponse"];
            var           userProfile        = new UserProfile();


            //Contains the inputed variables
            var rawValues = (JObject)stepContext.Context.Activity.Value;

            foreach (var val in rawValues)
            {
                if (val.Key != "Domain")
                {
                    userProfile.GetType().GetProperty(val.Key.ToString()).SetValue(userProfile, val.Value.ToString());
                }
                else
                {
                    userProfile.Domain = val.Value.ToString();
                }
            }

            userProfile.DomainName        = userProfile.GivenName.Replace(" ", "") + userProfile.SurName.Replace(" ", "");
            userProfile.UserPrincipalName = userProfile.DomainName + userProfile.Domain;

            await OAuthHelpers.CreateUserAsync(stepContext.Context, tokenResponse, userProfile);

            return(await stepContext.EndDialogAsync(null, cancellationToken));
        }
Beispiel #5
0
        static private string ExecuteRequest(string url, WebParameterCollection param = null)
        {
            string req = url;

            if (Apikey == "")
            {
                Apikey = ConfigurationManager.AppSettings["rebrickableapikey"];
            }
            req += "?key=" + Apikey;
            if (param != null)
            {
                req += '&' + OAuthHelpers.Concatenate(param, "=", "&");
            }
            Debug.WriteLine($"{req}");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(req);

            try
            {
                HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
                Stream          dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                return(reader.ReadToEnd());
            }
            catch (Exception)
            {
                return("");
            }
        }
Beispiel #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="Callback"></param>
        /// <returns></returns>
        public String GetLoginUrl(String Token, String Callback)
        {
            CheckInformationSet();
            Dictionary <String, String> extraParams = new Dictionary <String, String>();

            extraParams.Add("application_name", ApplicationName);
            return(OAuthHelpers.GetOAuthLoginUrl(ConsumerKey, Token, Callback, Constants.LoginUrl, extraParams));
        }
Beispiel #7
0
        private static dynamic RetrieveUserInfo(string accessToken)
        {
            var uri = OAuthHelpers.BuildUri(ApiUrl, "oauth2/v1/userinfo", new NameValueCollection {
                { "access_token", accessToken }
            });

            var response = OAuthHelpers.GetObjectFromAddress(uri);

            return(response);
        }
Beispiel #8
0
        public async Task <People> SearchPeople(String Name, Int32 Limit       = 10, Boolean OnUserBehalf = true,
                                                PersonExpansion ExpansionLevel = PersonExpansion.Minimal)
        {
            Login.CheckInformationSet();

            Dictionary <String, String> extraParams = new Dictionary <String, String>();

            extraParams.Add("term", OAuthHelpers.Encode(Name));
            extraParams.Add("max_results", Limit.ToString());

            String tokenSecret = "";

            //String token = "";
            if (OnUserBehalf)
            {
                Account na = FlixSharp.Netflix.SafeReturnUserInfo();
                if (na != null)
                {
                    tokenSecret = na.TokenSecret;
                    extraParams.Add("oauth_token", na.Token);
                }
            }

            String personurl = OAuthHelpers.GetOAuthRequestUrl(Login.SharedSecret,
                                                               Login.ConsumerKey,
                                                               Constants.CatalogPeopleSearcUrl,
                                                               "GET",
                                                               tokenSecret,
                                                               extraParams);

            var persondoc = AsyncHelpers.NetflixLoadXDocumentAsync(personurl);

            People people = new People();

            switch (ExpansionLevel)
            {
            case PersonExpansion.Minimal:
                people.AddRange(from person
                                in (await persondoc).Element("people").Elements("person")
                                select new Person(PersonExpansion.Minimal)
                {
                    IdUrl = person.Element("id").Value,
                    Name  = person.Element("name").Value,
                    Bio   = (String)person.Element("bio")
                });
                break;

            case PersonExpansion.Complete:
                people.AddRange(await AsyncFiller.GetCompleteNetflixPersonDetails(await persondoc));
                break;
            }


            return(people);
        }
Beispiel #9
0
        public async Task <Titles> SearchTitles(String Title, Int32 Limit     = 10, Boolean OnUserBehalf = true,
                                                TitleExpansion ExpansionLevel = TitleExpansion.Minimal)
        {
            Login.CheckInformationSet();

            Dictionary <String, String> extraParams = new Dictionary <String, String>();

            extraParams.Add("term", FlixSharp.Helpers.OAuth.OAuthHelpers.Encode(Title));
            extraParams.Add("max_results", Limit.ToString());

            String tokenSecret = "";

            //String token = "";
            if (OnUserBehalf)
            {
                Account na = FlixSharp.Netflix.SafeReturnUserInfo();
                if (na != null)
                {
                    tokenSecret = na.TokenSecret;
                    extraParams.Add("oauth_token", na.Token);
                }
            }

            String titleurl = OAuthHelpers.GetOAuthRequestUrl(Login.SharedSecret,
                                                              Login.ConsumerKey,
                                                              Constants.CatalogTitleSearchUrl,
                                                              "GET",
                                                              tokenSecret,
                                                              extraParams);

            var moviedoc = AsyncHelpers.NetflixLoadXDocumentAsync(titleurl);

            Titles movies = new Titles();

            switch (ExpansionLevel)
            {
            case TitleExpansion.Minimal:
                movies.AddRange(await Fill.GetBaseTitleInfo(moviedoc, "catalog_title"));
                break;

            case TitleExpansion.Expanded:
                movies.AddRange(await AsyncFiller.GetExpandedMovieDetails(await moviedoc));
                break;

            case TitleExpansion.Complete:
                movies.AddRange(await AsyncFiller.GetCompleteNetflixMovieDetails(await moviedoc));
                break;
            }


            return(movies);
        }
        private string GetAuthenticationHeaderForRequest(Uri requestUri, HttpMethod method)
        {
            List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>(Constants.oauth_consumer_key, _apiKey),
                new KeyValuePair <string, string>(Constants.oauth_nonce, OAuthHelpers.GenerateNonce()),
                new KeyValuePair <string, string>(Constants.oauth_timestamp, OAuthHelpers.GenerateTimestamp()),
                new KeyValuePair <string, string>(Constants.oauth_signature_method, "HMAC-SHA1"),
                new KeyValuePair <string, string>(Constants.oauth_version, Constants.oauth_version_1a),
                new KeyValuePair <string, string>(Constants.oauth_token, _authToken),
            };

            string baseUri = requestUri.OriginalString;

            // We need to handle the case where the request comes with query parameters
            if (!string.IsNullOrEmpty(requestUri.Query))
            {
                baseUri = requestUri.OriginalString.Replace(requestUri.Query, "");

                foreach (var param in requestUri.Query.Split(new char[] { '?', '&' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var    values = param.Split('=');
                    string name   = values[0];
                    string value  = string.Empty;
                    if (values.Length > 1)
                    {
                        value = values[1];
                    }
                    parameters.Add(new KeyValuePair <string, string>(name, value));
                }
            }

            string baseString = OAuthHelpers.GenerateBaseString(baseUri, method.ToString(), parameters);

            Trace.WriteLine($"Base String: {baseString}");
            string sig = OAuthHelpers.EncodeValue(OAuthHelpers.GenerateHMACDigest(baseString, _secret, _authTokenSecret));

            parameters.Add(new KeyValuePair <string, string>(Constants.oauth_signature, sig));

            StringBuilder sb = new StringBuilder();

            foreach (var param in parameters)
            {
                if (param.Key.StartsWith("oauth"))
                {
                    sb.AppendFormat("{0}={1},", param.Key, System.Net.WebUtility.HtmlEncode(param.Value));
                }
            }
            sb.Remove(sb.Length - 1, 1);
            return(sb.ToString());
        }
Beispiel #11
0
        private string BuildAuthUri(string returnUrl)
        {
            var appId          = GetAppId();
            var returnUriValue = BuildCallbackUriValue();
            var authUri        = OAuthHelpers.BuildUri(OAuthUrl, "o/oauth2/auth", new NameValueCollection()
            {
                { "client_id", appId },
                { "redirect_uri", returnUriValue },
                { "response_type", "code" },
                { "scope", "email" },
                { "state", HttpUtility.UrlEncode(returnUrl) }
            });

            return(authUri);
        }
Beispiel #12
0
        private string RetrieveAccessToken(string authorizationCode)
        {
            var appId     = GetAppId();
            var appSecret = GetAppSecret();

            var returnUriValue = BuildCallbackUriValue();
            var param          = new NameValueCollection {
                { "client_id", appId },
                { "client_secret", appSecret },
                { "code", authorizationCode },
                { "grant_type", "authorization_code" },
                { "redirect_uri", returnUriValue },
            };
            var url = OAuthHelpers.BuildUri(OAuthUrl, "o/oauth2/token", new NameValueCollection());

            string accessToken = OAuthHelpers.GetObjectWithPost(url, param).access_token;

            return(accessToken);
        }
Beispiel #13
0
        private async Task <DialogTurnResult> ProcessStep2Async(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var tokenResponse = (TokenResponse)stepContext.Result;

            if (tokenResponse != null)
            {
                // We do not need to store the token in the bot. When we need the token we can
                // send another prompt. If the token is valid the user will not need to log back in.
                // The token will be available in the Result property of the task.

                // If we have the token use the user is authenticated so we may use it to make API calls.
                if (tokenResponse?.Token != null)
                {
                    var parts = ((string)stepContext.Values["command"] ?? string.Empty).ToLowerInvariant().Split(' ');

                    var command = parts[0];

                    if (command == "me")
                    {
                        await OAuthHelpers.ListMeAsync(stepContext.Context, tokenResponse);
                    }
                    else if (command.StartsWith("send"))
                    {
                        await OAuthHelpers.SendMailAsync(stepContext.Context, tokenResponse, parts[1]);
                    }
                    else if (command.StartsWith("recent"))
                    {
                        await OAuthHelpers.ListRecentMailAsync(stepContext.Context, tokenResponse);
                    }
                    else
                    {
                        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Your token is: {tokenResponse.Token}"), cancellationToken);
                    }
                }
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("We couldn't log you in. Please try again later."), cancellationToken);
            }

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
Beispiel #14
0
        private async Task <DialogTurnResult> ProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            Dictionary <string, object> args = (Dictionary <string, object>)stepContext.Options;
            TokenResponse tokenResponse      = (TokenResponse)args["TokenResponse"];
            var           userProfile        = (UserProfile)stepContext.Values[UserInfo];

            var rawValues = (JObject)stepContext.Context.Activity.Value;

            int selectValue = (int)rawValues.GetValue("SingleSelectVal");

            if (selectValue == 2)
            {
                await OAuthHelpers.RemoveUserAsync(stepContext.Context, tokenResponse, userProfile.UserPrincipalName);
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text($"{userProfile.DomainName} is not getting deleted"));
            }

            return(await stepContext.EndDialogAsync(null, cancellationToken));
        }
        private async Task <DialogTurnResult> ProcessStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (stepContext.Result != null)
            {
                // The token will be available in the Result property of the task.
                var tokenResponse = stepContext.Result as TokenResponse;

                // If we have the token use the user is authenticated so we may use it to make API calls.
                if (tokenResponse?.Token != null)
                {
                    var parts = ((string)stepContext.Values["command"] ?? string.Empty).ToLowerInvariant().Split(' ');

                    var command = parts[0];

                    if (command == "me")
                    {
                        await OAuthHelpers.ListMeAsync(stepContext.Context, tokenResponse);

                        //return await stepContext.NextAsync();
                    }

                    else
                    {
                        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Your token is: {tokenResponse.Token}"), cancellationToken);

                        return(await stepContext.NextAsync());
                    }
                }
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("We couldn't log you in. Please try again later."), cancellationToken);
            }

            return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
        }
Beispiel #16
0
 public static String SearchUrl(String SearchTerm, Int32 Limit = 10, Int32 Page = 1)
 {
     return(String.Format(Constants.SearchUrl, Login.ConsumerKey, OAuthHelpers.Encode(SearchTerm), Limit, Page));
 }
Beispiel #17
0
        /// <summary>
        /// Make a catalog/titles search request
        /// </summary>
        /// <param name="SearchTerm"></param>
        /// <param name="Limit"></param>
        /// <param name="OnUserBehalf">Make the request on the user's behalf if a
        /// GetCurrentUserNetflixUserInfo delegate was provided during creation.</param>
        /// <returns></returns>
        public async Task <SearchResults> SearchEverything(String SearchTerm, Int32 Limit       = 20, Boolean OnUserBehalf = true,
                                                           TitleExpansion TitleExpansionLevel   = TitleExpansion.Minimal,
                                                           PersonExpansion PersonExpansionLevel = PersonExpansion.Minimal)
        {
            Login.CheckInformationSet();

            Dictionary <String, String> extraParams = new Dictionary <String, String>();

            extraParams.Add("term", OAuthHelpers.Encode(SearchTerm));
            extraParams.Add("max_results", Limit.ToString());

            String tokenSecret = "";

            if (OnUserBehalf)
            {
                Account na = FlixSharp.Netflix.SafeReturnUserInfo();
                if (na != null)
                {
                    tokenSecret = na.TokenSecret;
                    extraParams.Add("oauth_token", na.Token);
                }
            }

            String personurl = OAuthHelpers.GetOAuthRequestUrl(Login.SharedSecret,
                                                               Login.ConsumerKey,
                                                               Constants.CatalogPeopleSearcUrl,
                                                               "GET",
                                                               tokenSecret,
                                                               extraParams);
            var persondoc = AsyncHelpers.NetflixLoadXDocumentAsync(personurl);

            String titleurl = OAuthHelpers.GetOAuthRequestUrl(Login.SharedSecret,
                                                              Login.ConsumerKey,
                                                              Constants.CatalogTitleSearchUrl,
                                                              "GET",
                                                              tokenSecret,
                                                              extraParams);
            var moviedoc = AsyncHelpers.NetflixLoadXDocumentAsync(titleurl);

            People people = new People();

            switch (PersonExpansionLevel)
            {
            case PersonExpansion.Minimal:
                people.AddRange(from person
                                in (await persondoc).Descendants("person")
                                select new Person(PersonExpansion.Minimal)
                {
                    IdUrl = person.Element("id").Value,
                    Name  = person.Element("name").Value,
                    Bio   = (String)person.Element("bio")
                });
                break;

            case PersonExpansion.Complete:
                people.AddRange(await AsyncFiller.GetCompleteNetflixPersonDetails(await persondoc));
                break;
            }

            Titles movies = new Titles();

            switch (TitleExpansionLevel)
            {
            case TitleExpansion.Minimal:
                movies.AddRange(await Fill.GetBaseTitleInfo(moviedoc, "catalog_title"));
                break;

            case TitleExpansion.Expanded:
                movies.AddRange(await AsyncFiller.GetExpandedMovieDetails(await moviedoc));
                break;

            case TitleExpansion.Complete:
                movies.AddRange(await AsyncFiller.GetCompleteNetflixMovieDetails(await moviedoc));
                break;
            }

            SearchResults sr = new SearchResults();

            sr.MovieResults  = movies;
            sr.PeopleResults = people;
            sr.SearchTerm    = SearchTerm;
            return(sr);
        }
        private async Task <DialogTurnResult> showAdaptiveCardAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if ((stepContext.Context.Activity.Text != null) || (stepContext.Context.Activity.Value != null))
            {
                // The token will be available in the Result property of the task.
                var tokenResponse = stepContext.Result as TokenResponse;

                List <Microsoft.Graph.User> users = new List <Microsoft.Graph.User>();
                var list = new List <Tuple <string, string> >();
                Dictionary <string, string> _teamsa = new Dictionary <string, string>();
                users = await OAuthHelpers.ListMeAsync(stepContext.Context, tokenResponse);

                try
                {
                    foreach (Microsoft.Graph.User u in users)
                    {
                        string dname = u.DisplayName;
                        string sname = u.Surname;
                        try
                        {
                            if (dname == null)
                            {
                                dname = "Test";
                            }
                            if (sname == null)
                            {
                                sname = "Test";
                            }
                        }
                        catch (Exception e) { }
                        //_teamsa.Add((JsonConvert.DeserializeObject(u.DisplayName.ToString())), (JsonConvert.DeserializeObject<Microsoft.Graph.User>(u.Surname.ToString())));
                        list.Add(Tuple.Create(dname, sname));
                        _teamsa.Add(dname, sname);
                    }
                }
                catch (Exception e)
                {
                    e.ToString();
                }
                List <string> _teamsType = new List <string>
                {
                    { "Public" },
                    { "Private" }
                };
                List <string> _teamsClassification = new List <string>
                {
                    { "Internal" },
                    { "External" },
                    { "Business" },
                    { "Protected" },
                    { "Important" },
                    { "Personal" }
                };

                //var choicesTeamOwners = _teamsa.Select(s => new AdaptiveChoice { Title = s.Key, Value = s.Key }).ToList();
                var choicesType = _teamsType.Select(s => new AdaptiveChoice {
                    Title = s, Value = s
                }).ToList();
                var choicesClassification = _teamsClassification.Select(s => new AdaptiveChoice {
                    Title = s, Value = s
                }).ToList();
                try
                {
                    var card = new AdaptiveCard
                    {
                        Version = new AdaptiveSchemaVersion(1, 0),
                        Body    =
                        {
                            new AdaptiveTextBlock("Team Name"),
                            new AdaptiveTextInput
                            {
                                Id = "Teamname",
                            },
                            new AdaptiveTextBlock("Description"),
                            new AdaptiveTextInput
                            {
                                Id = "Description",
                            },
                            new AdaptiveTextBlock("Team Owners"),
                            new AdaptiveChoiceSetInput
                            {
                                Choices       = choicesType,
                                Id            = "TeamOwners",
                                Style         = AdaptiveChoiceInputStyle.Compact,
                                IsMultiSelect = false
                            },
                            new AdaptiveTextBlock("Type"),
                            new AdaptiveChoiceSetInput
                            {
                                Choices       = choicesType,
                                Id            = "Type",
                                Style         = AdaptiveChoiceInputStyle.Compact,
                                IsMultiSelect = false
                            },
                            new AdaptiveTextBlock("Classification"),
                            new AdaptiveChoiceSetInput
                            {
                                Choices       = choicesClassification,
                                Id            = "Classification",
                                Style         = AdaptiveChoiceInputStyle.Compact,
                                IsMultiSelect = false
                            }
                        },
                        Actions = new List <AdaptiveAction>
                        {
                            new AdaptiveSubmitAction
                            {
                                Title = "Create Team",
                                Type  = "Action.Submit"
                            }
                        }
                    };

                    return(await stepContext.PromptAsync($"{ nameof(SiteRequestDialog)}.ShowCard",
                                                         new PromptOptions
                    {
                        // Choices = ChoiceFactory.ToChoices(_teamsa.Select(pair => pair.Value).ToList()),
                        Prompt = (Activity)MessageFactory.Attachment(new Attachment
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(card))
                        })
                    },
                                                         cancellationToken));
                }
                catch (Exception e)
                { e.ToString(); }
                return(await stepContext.NextAsync());
            }
            else
            {
                return(await stepContext.EndDialogAsync());
            }
        }
Beispiel #19
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="Token"></param>
 /// <param name="TokenSecret"></param>
 /// <returns></returns>
 public String GetAccessUrl(String Token, String TokenSecret)
 {
     CheckInformationSet();
     return(OAuthHelpers.GetOAuthAccessUrl(SharedSecret, ConsumerKey, Constants.AccessUrl, Token, TokenSecret));
 }
Beispiel #20
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public String GetRequestUrl()
 {
     CheckInformationSet();
     return(OAuthHelpers.GetOAuthRequestUrl(SharedSecret, ConsumerKey, Constants.RequestUrl, "GET"));
 }
        public async Task PerformAuthenticationAsync(Action activateCallback)
        {
            // Clear any previous tokens
            this.AccessToken  = null;
            this.RefreshToken = null;

            // Generates state and PKCE values.
            string state         = OAuthHelpers.RandomDataBase64url(32);
            string codeVerifier  = OAuthHelpers.RandomDataBase64url(32);
            string codeChallenge = OAuthHelpers.Base64urlencodeNoPadding(OAuthHelpers.Sha256(codeVerifier));

            // Creates a redirect URI using an available port on the loopback address.
            string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, OAuthHelpers.GetRandomUnusedPort());

            Output("redirect URI: " + redirectURI);

            // Creates an HttpListener to listen for requests on that redirect URI.
            var http = new HttpListener();

            http.Prefixes.Add(redirectURI);
            Output("Listening..");
            http.Start();

            // Creates the OAuth 2.0 authorization request.
            string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
                                                        AuthorizationEndpoint,
                                                        System.Uri.EscapeDataString(redirectURI),
                                                        ClientID,
                                                        state,
                                                        codeChallenge,
                                                        CodeChallengeMethod);

            // Opens request in the browser.
            System.Diagnostics.Process.Start(authorizationRequest);

            // Waits for the OAuth authorization response.
            var context = await http.GetContextAsync();

            // Brings this app back to the foreground.
            activateCallback?.Invoke();

            // Sends an HTTP response to the browser.
            var response = context.Response;

            var buffer = Encoding.UTF8.GetBytes(ResponseString);

            response.ContentLength64 = buffer.Length;
            var  responseOutput = response.OutputStream;
            Task responseTask   = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
            {
                responseOutput.Close();
                http.Stop();
                Console.WriteLine("HTTP server stopped.");
            });

            // Checks for errors.
            if (context.Request.QueryString.Get("error") != null)
            {
                throw new OAuthException(string.Format("OAuth authorization error: {0}.", context.Request.QueryString.Get("error")));
            }

            if (context.Request.QueryString.Get("code") == null ||
                context.Request.QueryString.Get("state") == null)
            {
                throw new OAuthException("Malformed authorization response. " + context.Request.QueryString);
            }

            // extracts the code
            var code           = context.Request.QueryString.Get("code");
            var incoming_state = context.Request.QueryString.Get("state");

            // Compares the receieved state to the expected value, to ensure that
            // this app made the request which resulted in authorization.
            if (incoming_state != state)
            {
                throw new OAuthException(string.Format("Received request with invalid state ({0})", incoming_state));
            }

            Output("Authorization code: " + code);

            // Starts the code exchange at the Token Endpoint.
            await PerformCodeExchange(code, codeVerifier, redirectURI);
        }