Beispiel #1
0
        /// <summary>
        /// return OAuth 2.0 Credentials. If the token is expired, it will first attempt to refresh the token.
        /// </summary>
        /// <param name="uri">Ignored.</param>
        /// <param name="authType">Ignored.</param>
        /// <exception cref="WebException">May occour when refreshing the token</exception>
        public NetworkCredential GetCredential(Uri uri, string authType)
        {
            if (AccessTokenExpiration != null && RefreshToken != null && AccessTokenExpiration.Subtract(DateTime.Now).TotalSeconds < RefreshThreshold)
            {
                OAuthCredential newCreds = _client.RefreshAccessToken(RefreshToken);
                AccessToken = newCreds.AccessToken;

                // a new refresh token may be issued, per 5.2
                if (newCreds.RefreshToken != null)
                {
                    RefreshToken          = newCreds.RefreshToken;
                    AccessTokenExpiration = newCreds.AccessTokenExpiration;
                    ExpiresIn             = newCreds.ExpiresIn;
                }
                else
                {
                    // otherwise, calculate the next refresh time
                    AccessTokenExpiration = DateTime.Now.AddSeconds(ExpiresIn);
                }
            }

            return(new NetworkCredential("OAuth", AccessToken));
        }
Beispiel #2
0
        /// <summary>
        /// TODO Comment
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        private OAuthCredential RequestOrRefreshAuthToken(NameValueCollection values)
        {
            OAuthCredential credentials;

            try
            {
                using (var client = new WebClient {
                    BaseAddress = _tokenUri.ToString()
                })
                {
                    // Construct the Access Token Request request, per OAuth 2.0 spec at 4.1.3, or Refresh Token request in section 6
                    values["scope"]         = _tokenEndpointScopeEncoded;
                    values["client_id"]     = HttpUtility.HtmlEncode(_clientId);
                    values["client_secret"] = HttpUtility.HtmlEncode(_clientSecret.ConvertToString());

                    var responseBytes = client.UploadValues(_tokenUri.AbsolutePath, "POST", values);

                    OAuthAccessTokenResponseJson resultJson = null;
                    try
                    {
                        JavaScriptSerializer ser = new JavaScriptSerializer();
                        resultJson = ser.Deserialize <OAuthAccessTokenResponseJson>(client.Encoding.GetString(responseBytes));
                    }
                    // catch various exceptions and filter them to a ProtocolViolationException, as if not, it is a violation of OAuth protocol.
                    catch (ArgumentException)
                    {
                        throw new ProtocolViolationException("Response could not be parsed");
                    }
                    catch (InvalidOperationException)
                    {
                        throw new ProtocolViolationException("Response could not be parsed");
                    }

                    if (resultJson != null)
                    {
                        if (string.IsNullOrEmpty(resultJson.refresh_token))
                        {
                            // Create a new set of credentials that doesn't expire
                            credentials = new OAuthCredential(resultJson.access_token);
                        }
                        else
                        {
                            try
                            {
                                // expires_in should always be with a refresh_token.
                                int expires_in = Int32.Parse(resultJson.expires_in);
                                credentials = new OAuthCredential(resultJson.access_token, resultJson.refresh_token, expires_in, this);
                            }
                            catch (FormatException)
                            {
                                throw new ProtocolViolationException("expires_in is malformed");
                            }
                        }
                    }
                    else
                    {
                        throw new ProtocolViolationException("Response wasn't in JSON format.");
                    }
                }
            }
            catch (WebException ex)
            {
                // Error conditions are returned as 400 Bad Request, per section 5.2 of the OAuth 2.0 spec
                if (ex.Response != null && ((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.BadRequest)
                {
                    OAuthErrorException errorEx = OAuthErrorException.FromWebException(ex);
                    if (errorEx != null)
                    {
                        throw errorEx;
                    }
                }

                throw;
            }

            return(credentials);
        }