Beispiel #1
0
        private static async Task <Token> RefreshToken(ClientIdentifier clientIdentifier, Token tokenData)
        {
            Token resultToken = null;

            HttpContent requestContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("client_secret", clientIdentifier.GetSecret()),
                new KeyValuePair <string, string>("grant_type", "refresh_token"),
                new KeyValuePair <string, string>("refresh_token", tokenData.refreshToken),
                new KeyValuePair <string, string>("client_id", clientIdentifier.GetID()),
            });

            requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            try
            {
                HttpClient          client   = new HttpClient();
                HttpResponseMessage response = await client.PostAsync(TokenApi, requestContent);

                if (response.IsSuccessStatusCode)
                {
                    string replyJson = await response.Content.ReadAsStringAsync();

                    resultToken = CreateToken(replyJson);
                    resultToken.refreshToken = tokenData.refreshToken;
                }
            }
            catch (Exception) { }

            return(resultToken);
        }
Beispiel #2
0
        private static async Task <Token> RequestToken(ClientIdentifier clientIdentifier)
        {
            // prepare listen server for receiving token data
            if (!HttpListener.IsSupported || clientIdentifier == null)
            {
                return(null);
            }

            int    listenPort    = FindListenPort();
            string authListenUri = "http://localhost:" + listenPort + "/auth_response/";

            httpListener = new HttpListener();
            httpListener.Prefixes.Add(authListenUri);
            httpListener.Start();

            // send authorization request: open in default browser
            string authRequestUri = RequestAccessApi +
                                    "?redirect_uri=" + Uri.EscapeDataString(authListenUri) +
                                    "&prompt=consent" +
                                    "&response_type=code" +
                                    "&client_id=" + clientIdentifier.GetID() +
                                    "&scope=" + Uri.EscapeDataString(AccessScopeAppSettings) +
                                    "&access_type=offline";

            Process.Start(authRequestUri);

            // wait for reponse
            string authorizationCode = null;
            {
                HttpListenerContext listenContext = null;
                try
                {
                    listenContext = await Task.Factory.FromAsync(httpListener.BeginGetContext(null, null), httpListener.EndGetContext);
                }
                catch (Exception) { listenContext = null; }

                if (listenContext != null)
                {
                    Uri requestUrl = listenContext.Request.Url;

                    ILookup <string, string> queryLookup = requestUrl.Query.TrimStart('?')
                                                           .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(k => k.Split('='))
                                                           .Where(k => k.Length == 2)
                                                           .ToLookup(a => a[0], a => Uri.UnescapeDataString(a[1]), StringComparer.OrdinalIgnoreCase);
                    authorizationCode = queryLookup["code"].FirstOrDefault();

                    string responseString = "<html><title>Google account verification</title><body>Received verification code. You may now close this window.</body></html>";
                    byte[] buffer         = Encoding.UTF8.GetBytes(responseString);

                    HttpListenerResponse listenResponse = listenContext.Response;
                    listenResponse.ContentLength64 = buffer.Length;
                    listenResponse.OutputStream.Write(buffer, 0, buffer.Length);
                    listenResponse.OutputStream.Close();
                }
            }

            // send token grant request: no user ui needed
            Token resultToken = null;

            if (!string.IsNullOrEmpty(authorizationCode))
            {
                HttpContent tokenGrantContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("code", authorizationCode),
                    new KeyValuePair <string, string>("redirect_uri", authListenUri),
                    new KeyValuePair <string, string>("client_id", clientIdentifier.GetID()),
                    new KeyValuePair <string, string>("client_secret", clientIdentifier.GetSecret()),
                    new KeyValuePair <string, string>("scope", AccessScopeAppSettings),
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                });

                tokenGrantContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

                try
                {
                    HttpClient          client             = new HttpClient();
                    HttpResponseMessage tokenGrantResponse = await client.PostAsync(TokenApi, tokenGrantContent);

                    if (tokenGrantResponse.IsSuccessStatusCode)
                    {
                        string replyJson = await tokenGrantResponse.Content.ReadAsStringAsync();

                        resultToken = CreateToken(replyJson);
                    }
                }
                catch (Exception) { }
            }

            if (httpListener != null && httpListener.IsListening)
            {
                httpListener.Close();
                httpListener = null;
            }

            return(resultToken);
        }