Exemple #1
0
        public async Task <AuthorizationResponse> GetAuthorizationAsync(string accessToken)
        {
            string responseJson;

            var requestUri = new Uri(launchpadUri, "authorization.json");

            using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri))
            {
                requestMessage.Headers.UserAgent.TryParseAdd(userAgent);
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                using (var httpClient = httpClientPool.Create())
                    using (var responseMessage = await httpClient.SendAsync(requestMessage))
                    {
                        await HttpResponseUtils.EnsureSuccessAsync(responseMessage);

                        responseJson = await responseMessage.Content.ReadAsStringAsync();
                    }
            }

            return(JsonConvert.DeserializeObject <AuthorizationResponse>(responseJson));
        }
Exemple #2
0
        private async Task <string> GetAuthenticityTokenAsync(Uri requestUri, string basecampCookieString)
        {
            string authenticityToken;

            using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri))
            {
                InitializeBrowserRequest(requestMessage);
                requestMessage.Headers.TryAddWithoutValidation("Cookie", basecampCookieString);

                using (var httpClient = httpClientPool.Create(new HttpClientHandlerOptions()))
                    using (var responseMessage = await httpClient.SendAsync(requestMessage))
                    {
                        await HttpResponseUtils.EnsureSuccessAsync(responseMessage);

                        var responseHtml = await responseMessage.Content.ReadAsStringAsync();

                        authenticityToken = ParseInputValue(responseHtml, "authenticity_token");
                    }
            }

            return(authenticityToken);
        }
Exemple #3
0
        public async Task <AccessTokenSource> AuthenticateVerificationCodeAsync(string verificationCode)
        {
            string responseJson;

            var requestUri = new Uri(launchpadUri, "authorization/token");

            using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri))
            {
                requestMessage.Content = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    ["type"]          = "web_server",
                    ["client_id"]     = oauthOptions.ClientId,
                    ["redirect_uri"]  = oauthOptions.RedirectUrl,
                    ["client_secret"] = oauthOptions.ClientSecret,
                    ["code"]          = verificationCode
                });
                requestMessage.Headers.UserAgent.TryParseAdd(userAgent);

                using (var httpClient = httpClientPool.Create())
                    using (var responseMessage = await httpClient.SendAsync(requestMessage))
                    {
                        await HttpResponseUtils.EnsureSuccessAsync(responseMessage);

                        responseJson = await responseMessage.Content.ReadAsStringAsync();
                    }
            }

            var tokenResponse            = JsonConvert.DeserializeObject <TokenResponse>(responseJson);
            var accessTokenSourceOptions = new AccessTokenSourceOptions(
                tokenUri: new Uri(launchpadUri, "authorization/token"),
                oauthOptions: oauthOptions,
                refreshToken: tokenResponse.RefreshToken
                );
            var accessTokenSource = new AccessTokenSource(accessTokenSourceOptions);

            accessTokenSource.LoadToken(tokenResponse);
            return(accessTokenSource);
        }
Exemple #4
0
        public async Task <AccessTokenSource> AuthenticateCookieAsync(string basecampCookieString, string username)
        {
            // We probably need an authenticity token from what's supposed to be the page before this one.
            var authenticityToken = await GetAuthenticityTokenAsync(
                requestUri : new Uri(launchpadUri, $"authorization/new?type=web_server&client_id={Uri.EscapeDataString(oauthOptions.ClientId)}&redirect_uri={oauthOptions.RedirectUrl}"),
                basecampCookieString : basecampCookieString
                );

            string verificationCode;

            var requestUri = new Uri(launchpadUri, "authorization");

            using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri))
            {
                requestMessage.Content = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    ["utf8"] = "✓",
                    ["authenticity_token"] = authenticityToken,
                    ["client_id"]          = oauthOptions.ClientId,
                    ["client_secret"]      = "",
                    ["type"]         = "web_server",
                    ["state"]        = "",
                    ["redirect_uri"] = oauthOptions.RedirectUrl,
                    ["commit"]       = ""
                });

                InitializeBrowserRequest(requestMessage);
                requestMessage.Headers.Referrer = new Uri(launchpadUri, $"signin?login_hint={Uri.EscapeDataString(username)}");
                requestMessage.Headers.TryAddWithoutValidation("Cookie", basecampCookieString);
                using (var httpClient = httpClientPool.Create(new HttpClientHandlerOptions(allowAutoRedirect: false)))
                    using (var responseMessage = await httpClient.SendAsync(requestMessage))
                    {
                        await HttpResponseUtils.EnsureSuccessAsync(responseMessage, allowRedirect : true);

                        if (responseMessage.StatusCode != System.Net.HttpStatusCode.Redirect)
                        {
                            throw new BasecampResponseException($"Expected a redirect for authorization/new request but was {responseMessage.StatusCode}")
                                  {
                                      RequestUri         = requestUri,
                                      ResponseStatusCode = responseMessage.StatusCode,
                                  };
                        }

                        var redirectLocation = responseMessage.Headers.Location;
                        if (redirectLocation == null)
                        {
                            throw new BasecampResponseException($"Expected a redirect location for authorization/new request")
                                  {
                                      RequestUri         = requestUri,
                                      ResponseStatusCode = responseMessage.StatusCode,
                                  };
                        }

                        // Location: urn:ietf:wg:oauth:2.0:oob?code=de615fc1
                        var queryStringPairs = ParseQueryString(redirectLocation.Query);
                        verificationCode = queryStringPairs.Where(kv => kv.Key == "code").Select(kv => kv.Value).FirstOrDefault();
                        if (verificationCode == null)
                        {
                            throw new BasecampResponseException($"Expected verification code for authorization/new request but url was <{redirectLocation}>")
                                  {
                                      RequestUri         = requestUri,
                                      ResponseStatusCode = responseMessage.StatusCode,
                                  };
                        }
                    }
            }

            return(await AuthenticateVerificationCodeAsync(verificationCode));
        }