Ejemplo n.º 1
0
        /// <summary>
        /// Queries the access token from the specified authorization code.
        /// </summary>
        /// <param name="returnUrl">The return URL.</param>
        /// <param name="authorizationCode">The authorization code.</param>
        /// <returns>
        /// The access token
        /// </returns>
        protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
        {
            string formData = UriUtility.CreateQueryString(
                new UriParameter("client_id", _appId),
                new UriParameter("client_secret", _appSecret),
                new UriParameter("code", authorizationCode),
                new UriParameter("grant_type", "authorization_code"),
                new UriParameter("redirect_uri", returnUrl.GetLeftPart(UriPartial.Path))); // Google OAuth 2 doesn't like query parameters.

            var request = WebRequest.Create(TokenEndpoint);

            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = formData.Length;
            request.Method        = "POST";

            using (var stream = request.GetRequestStream())
            {
                var writer = new StreamWriter(stream);
                writer.Write(formData);
                writer.Flush();
            }

            var response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (var stream = response.GetResponseStream())
                {
                    var data = OAuthHelpers.Deserialize <OAuth2AccessTokenData>(stream);
                    if (data != null)
                    {
                        return(data.AccessToken);
                    }
                }
            }
            return(null);
        }