コード例 #1
0
        public TwitterOAuthMessageHandler(OAuthCredential oAuthCredential, OAuthSignatureEntity signatureEntity,
            TwitterQueryCollection parameters, HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
            //TODO: Parameters needs to come here as encoded so that they can be encoded twice
            //      for the signature base. Handle that.

            //TODO: We don't even need to get parameters seperately. We can get them through
            //      query string and by reading the body but reading the body is a overhead here.

            _oAuthState = new OAuthState() {
                Credential = new OAuthCredentialState() {
                    ConsumerKey = oAuthCredential.ConsumerKey,
                    //encode it here first
                    CallbackUrl = OAuthUtil.PercentEncode(oAuthCredential.CallbackUrl),
                    Token = oAuthCredential.Token
                },
                SignatureEntity = new OAuthSignatureEntityState() {
                    ConsumerSecret = signatureEntity.ConsumerSecret,
                    TokenSecret = signatureEntity.TokenSecret
                },
                Parameters = parameters,
                Nonce = GenerateNonce(),
                SignatureMethod = GetOAuthSignatureMethod(),
                Timestamp = GenerateTimestamp(),
                Version = GetVersion()
            };
        }
コード例 #2
0
        private string GenerateAuthHeader(OAuthState oAuthState, HttpRequestMessage request)
        {
            SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>();
            sortedDictionary.Add(Constants.OAuthNonce, OAuthUtil.PercentEncode(oAuthState.Nonce));
            sortedDictionary.Add(Constants.OAuthSignatureMethod, OAuthUtil.PercentEncode(oAuthState.SignatureMethod));
            sortedDictionary.Add(Constants.OAuthTimestamp, OAuthUtil.PercentEncode(oAuthState.Timestamp));
            sortedDictionary.Add(Constants.OAuthConsumerKey, OAuthUtil.PercentEncode(oAuthState.Credential.ConsumerKey));
            sortedDictionary.Add(Constants.OAuthVersion, OAuthUtil.PercentEncode(oAuthState.Version));

            if (!string.IsNullOrEmpty(_oAuthState.Credential.Token))
                sortedDictionary.Add(Constants.OAuthToken, OAuthUtil.PercentEncode(oAuthState.Credential.Token));

            //don't encode it here again.
            //we already did that and this auth header field doesn't require it to be encoded twice
            if (!string.IsNullOrEmpty(_oAuthState.Credential.CallbackUrl))
                sortedDictionary.Add(Constants.OAuthCallback, oAuthState.Credential.CallbackUrl);

            StringBuilder strBuilder = new StringBuilder();
            var valueFormat = "{0}=\"{1}\",";

            sortedDictionary.ForEach(x => {
                strBuilder.AppendFormat(valueFormat, x.Key, x.Value);
            });

            //oAuth parameters has to be sorted before sending, but signature has to be at the end of the authorization request
            //http://stackoverflow.com/questions/5591240/acquire-twitter-request-token-failed
            strBuilder.AppendFormat(valueFormat, Constants.OAuthSignature, OAuthUtil.PercentEncode(GenerateSignature(oAuthState, request)));

            return strBuilder.ToString().TrimEnd(',');
        }
コード例 #3
0
        public ActionResult Authenticate(string success, string failure, string state)
        {
            string key = Guid.NewGuid().ToStringValue();

            OAuthState authState = new OAuthState();

            authState.FailureUrl = failure;
            authState.SuccessUrl = success;
            authState.State      = state;

            this.stateManager.SaveState(key, authState);
            UrlBuilder urlBuilder = new UrlBuilder(SocialApiSetting.BuildUrl(this.context.Config.Social.Twitter.Domain, "social/twitter/authorize"));

            urlBuilder.QueryString.Add("state", key);

            TwitterClient client = new TwitterClient(this.context.Config.Social.Twitter.AppKey,
                                                     this.context.Config.Social.Twitter.AppSecret);

            var tempCredential = client.GetRequestToken(urlBuilder.ToString());

            if (tempCredential == null || !tempCredential.OAuthCallbackConfirmed)
            {
                return(new RedirectResult(failure));
            }

            var           authorizationUrl = client.BuildAuthorizationUrl(tempCredential);
            ITokenManager tokenManager     = Container.Get <ITokenManager>();

            tokenManager.SaveRequestToken(key, tempCredential);
            return(new RedirectResult(authorizationUrl));
        }
コード例 #4
0
        public ActionResult Authenticate(string success, string failure, string permissions, string state, bool offline)
        {
            string key = Guid.NewGuid().ToStringValue();

            OAuthState authState = new OAuthState();

            authState.FailureUrl = failure;
            authState.SuccessUrl = success;
            authState.State      = state;

            this.stateManager.SaveState(key, authState);

            IDictionary <string, string> parameters = new Dictionary <string, string>();

            if (offline)
            {
                parameters.Add("access_type", "offline");
            }

            List <string> permissionList = new List <string>();

            if (!string.IsNullOrWhiteSpace(permissions))
            {
                permissionList.AddRange(permissions.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries));
            }

            GoogleClient client = new GoogleClient(this.context.Config.Social.Google.AppID,
                                                   this.context.Config.Social.Google.AppSecret);

            string authorizationUrl = client.BuildAuthorizationUrl(SocialApiSetting.BuildUrl(this.context.Config.Social.Google.Domain, "social/google/authorize"), permissionList, key, parameters);

            return(new RedirectResult(authorizationUrl));
        }
コード例 #5
0
 protected OAuth2Base(string clientId, string redirectUrl, string scope, string authorizationUrl)
 {
     ClientId         = clientId;
     RedirectUrl      = redirectUrl;
     Scope            = scope;
     AuthorizationUrl = authorizationUrl;
     OAuthState       = OAuthState.INITIALIZED;
 }
コード例 #6
0
        public ActionResult Cancel(string state)
        {
            OAuthState authState = this.stateManager.GetState(state);

            if (authState == null)
            {
                throw new InvalidOperationException("Invalid Authorization State");
            }

            UrlBuilder redirectBuilder = new UrlBuilder(authState.FailureUrl);

            return(new RedirectResult(redirectBuilder.ToString()));
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: dragthor/BridgeStack
        private static void GetOAuthRoute()
        {
            var state = new OAuthState();

            state.Add("example", "value");
            state.Add("another", "string");
            string value = oauth.GetExplicitOAuthApprovalUri(new OAuthScope
            {
                ReadInbox = true,
                NoExpiry  = true
            }, state);

            Console.WriteLine(value);
        }
コード例 #8
0
        public override string GetRedirectUrl(string state, string successUrl, string failureUrl)
        {
            if (string.IsNullOrWhiteSpace(this.BusinessEmail))
            {
                throw new InvalidOperationException("BusinessEmail is required");
            }

            var webContext = Container.Get <IWebContext>();

            this.Settings.SuccessUrl = webContext.BuildUrl("payment/gateway/paypal/wps/success?state=" + state);
            this.Settings.CancelUrl  = webContext.BuildUrl("payment/gateway/paypal/wps/cancel?state=" + state);
            IDictionary <string, string> dictionary = this.Settings.GetValues();

            dictionary.Add("charset", "utf-8");
            dictionary.Add("business", this.BusinessEmail);

            IOAuthStateManager stateManager = Container.Get <IOAuthStateManager>();
            string             key          = state;

            OAuthState authState = new OAuthState();

            authState.FailureUrl = failureUrl;
            authState.SuccessUrl = successUrl;
            authState.State      = this.BusinessEmail;
            stateManager.SaveState(key, authState);

            dictionary.Add("notify_url", webContext.BuildUrl("payment/gateway/paypal/wps/verifyipn?state=" + state));

            UrlBuilder builder = new UrlBuilder(this.Server.ToDescription());

            builder.QueryString.Add("cmd", "_xclick");
            builder.QueryString.Add("bn", "LM_BuyNow_WPS_IN");

            foreach (KeyValuePair <string, string> setting in dictionary)
            {
                builder.QueryString.Add(setting.Key, setting.Value);
            }

            IDictionary <string, string> dictionary2 = this.PaymentDetails.GetValues();

            foreach (KeyValuePair <string, string> setting in dictionary2)
            {
                builder.QueryString.Add(setting.Key, setting.Value);
            }


            return(builder.ToString());
        }
コード例 #9
0
        public ActionResult Authorize(string state, string oauth_verifier, string denied)
        {
            OAuthState authState = this.stateManager.GetState(state);

            UrlBuilder errorUrlBuilder = new UrlBuilder(authState.FailureUrl);

            if (authState == null)
            {
                throw new InvalidOperationException("Invalid Authorization State");
            }

            if (!string.IsNullOrWhiteSpace(oauth_verifier))
            {
                TwitterClient client = new TwitterClient(this.context.Config.Social.Twitter.AppKey,
                                                         this.context.Config.Social.Twitter.AppSecret);
                ITokenManager tokenManager = Container.Get <ITokenManager>();
                var           token        = tokenManager.GetRequestToken(state);

                if (token != null)
                {
                    OAuth1TokenCredential credential = client.GetAccessToken(token, oauth_verifier);

                    if (credential != null && credential.Success)
                    {
                        UrlBuilder redirectBuilder = new UrlBuilder(authState.SuccessUrl);
                        redirectBuilder.QueryString.Add("token", credential.Token);
                        redirectBuilder.QueryString.Add("secret", credential.Secret);

                        if (!string.IsNullOrWhiteSpace(authState.State))
                        {
                            redirectBuilder.QueryString.Add("state", authState.State);
                        }

                        return(new RedirectResult(redirectBuilder.ToString()));
                    }
                }
            }


            if (!string.IsNullOrWhiteSpace(denied))
            {
                errorUrlBuilder.QueryString.Add("denied", "true");
            }

            return(new RedirectResult(errorUrlBuilder.ToString()));
        }
コード例 #10
0
        public ActionResult Authorize(string state, string code, string error)
        {
            OAuthState authState = this.stateManager.GetState(state);

            if (authState == null)
            {
                throw new InvalidOperationException("Invalid Authorization State");
            }

            UrlBuilder errorUrlBuilder = new UrlBuilder(authState.FailureUrl);

            if (string.IsNullOrWhiteSpace(error))
            {
                GoogleClient client = new GoogleClient(this.context.Config.Social.Google.AppID, this.context.Config.Social.Google.AppSecret);

                var credential = client.GetAccessToken(code, SocialApiSetting.BuildUrl(this.context.Config.Social.Google.Domain, "social/google/authorize"));
                if (credential != null && credential.Success)
                {
                    UrlBuilder redirectBuilder = new UrlBuilder(authState.SuccessUrl);
                    redirectBuilder.QueryString.Add("token", credential.Token);
                    redirectBuilder.QueryString.Add("refreshToken", credential.RefreshToken);
                    redirectBuilder.QueryString.Add("expiresIn", credential.ExpiresIn.ToStringValue());

                    if (!string.IsNullOrWhiteSpace(authState.State))
                    {
                        redirectBuilder.QueryString.Add("state", authState.State);
                    }

                    return(new RedirectResult(redirectBuilder.ToString()));
                }

                if (credential != null && !string.IsNullOrWhiteSpace(credential.ErrorCode))
                {
                    errorUrlBuilder.QueryString.Add("code", credential.ErrorCode);
                    errorUrlBuilder.QueryString.Add("message", credential.ErrorMessage);
                }
            }
            errorUrlBuilder.QueryString.Add("code", error);


            return(new RedirectResult(errorUrlBuilder.ToString()));
        }
コード例 #11
0
        public ActionResult VerifyIPN(string state)
        {
            OAuthState authState = this.stateManager.GetState(state);

            if (authState == null)
            {
                throw new InvalidOperationException("Invalid Authorization State");
            }

            string businessEmail = authState.State;

            if (!string.IsNullOrWhiteSpace(businessEmail))
            {
                string recieverEmail = this.Request["receiver_email"];

                if (!recieverEmail.IsEmpty() && recieverEmail.EqualsIgnoreCase(businessEmail))
                {
                    ServerType serverType = ServerType.Live;

                    if (this.Request["test_ipn"] != null)
                    {
                        //File.WriteAllText(path, "test_ipn");
                        serverType = ServerType.Live;
                    }

                    string serverUrl = serverType.ToDescription();

                    RestClient  client  = new RestClient();
                    RestRequest request = new RestRequest(serverUrl, RequestMode.UrlEncoded);

                    request.AddBody("cmd", "_notify-validate");

                    foreach (string postKey in this.Request.Params)
                    {
                        request.AddBody(postKey, this.Request[postKey]);
                    }

                    RestResponse restResponse = client.Post(request);

                    if (restResponse.Completed)
                    {
                        if (restResponse.Content == "VERIFIED")
                        {
                            var handler = Container.TryGet <IIPNProcessor>();

                            if (handler != null)
                            {
                                IPNResponse ipnResponse = new IPNResponse();
                                ipnResponse.BusinessEmail      = businessEmail;
                                ipnResponse.ReceiverEmail      = this.Request["receiver_email"];
                                ipnResponse.ReceiverID         = this.Request["receiver_id"];
                                ipnResponse.TransactionID      = this.Request["txn_id"];
                                ipnResponse.TransactionSubject = this.Request["transaction_subject"];
                                ////this.TransactionType = (TransactionType)Reflector.DescriptionToEnum(typeof(TransactionType), this.Context.Request["txn_type"]);
                                ////this.ReceiverCountry = (CountryCode)Reflector.DescriptionToEnum(typeof(CountryCode), this.Context.Request["residence_country"]);
                                ipnResponse.Custom = this.Request["custom"];
                                ipnResponse.ParentTransactionID = this.Request["parent_txn_id"];
                                ipnResponse.Payment.Parse(this.Request.Params);

                                handler.Process(ipnResponse);
                            }
                        }
                    }
                }
            }

            return(new EmptyResult());
        }
コード例 #12
0
        private string GenerateSignature(OAuthState oAuthState, HttpRequestMessage request)
        {
            //https://dev.twitter.com/docs/auth/creating-signature
            //http://garyshortblog.wordpress.com/2011/02/11/a-twitter-oauth-example-in-c/

            //This dictionary will hold the twice-encoded values
            SortedDictionary<string, string> signatureBaseCollection = new SortedDictionary<string, string>();

            //Required for all requests
            signatureBaseCollection.Add(Constants.OAuthConsumerKey, oAuthState.Credential.ConsumerKey);
            signatureBaseCollection.Add(Constants.OAuthNonce, oAuthState.Nonce);
            signatureBaseCollection.Add(Constants.OAuthVersion, oAuthState.Version);
            signatureBaseCollection.Add(Constants.OAuthTimestamp, oAuthState.Timestamp);
            signatureBaseCollection.Add(Constants.OAuthSignatureMethod, oAuthState.SignatureMethod);

            //Parameters
            if (oAuthState.Parameters != null) {

                //these are already encoded. At the string building phase,
                //they will be encoded one more time.
                oAuthState.Parameters.ForEach(x => signatureBaseCollection.Add(x.Key, x.Value));
            }

            //Optionals
            if (!string.IsNullOrEmpty(oAuthState.Credential.Token))
                signatureBaseCollection.Add(Constants.OAuthToken, oAuthState.Credential.Token);

            //this needs to be encoded twice. So, we leave it as it is to be encode one more time
            if (!string.IsNullOrEmpty(oAuthState.Credential.CallbackUrl))
                signatureBaseCollection.Add(Constants.OAuthCallback, oAuthState.Credential.CallbackUrl);

            //Build the signature
            StringBuilder strBuilder = new StringBuilder();

            //these two ampersand chars needs not to be encoded
            strBuilder.AppendFormat("{0}&", request.Method.Method.ToUpper());
            strBuilder.AppendFormat("{0}&", OAuthUtil.PercentEncode(request.RequestUri.ToString()));

            //encode the values for signature base
            signatureBaseCollection.ForEach(x =>
                strBuilder.Append(
                    OAuthUtil.PercentEncode(string.Format("{0}={1}&", x.Key, x.Value))
                )
            );

            //Remove the trailing ambersand char from the signatureBase.
            //Remember, it's been urlEncoded so you have to remove the
            //last 3 chars - %26
            string baseSignatureString = strBuilder.ToString();
            baseSignatureString = baseSignatureString.Substring(0, baseSignatureString.Length - 3);

            //Build the signing key
            string signingKey = string.Format(
                "{0}&{1}", OAuthUtil.PercentEncode(oAuthState.SignatureEntity.ConsumerSecret),
                string.IsNullOrEmpty(oAuthState.SignatureEntity.TokenSecret) ? "" : OAuthUtil.PercentEncode(oAuthState.SignatureEntity.TokenSecret)
            );

            //Sign the request
            using (HMACSHA1 hashAlgorithm = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey))) {

                return Convert.ToBase64String(
                    hashAlgorithm.ComputeHash(
                        new ASCIIEncoding().GetBytes(baseSignatureString)
                    )
                );
            }
        }
コード例 #13
0
        /// <summary>
        /// Gets auth token and refresh tokens from auth code
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task <CompleteOAuthFlowResponse> CompleteOAuthFlow(CompleteOAuthFlowRequest request,
                                                                                 ServerCallContext context)
        {
            Logger.Info("Getting Auth and Refresh Token...");

            // get code from redirect url
            string code;
            var    uri = new Uri(request.RedirectUrl);

            try
            {
                code = HttpUtility.UrlDecode(HttpUtility.ParseQueryString(uri.Query).Get("code"));
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
                throw;
            }

            // token url parameters
            var redirectUrl = String.Format("{0}{1}{2}{3}", uri.Scheme, Uri.SchemeDelimiter, uri.Authority,
                                            uri.AbsolutePath);
            var clientId     = request.Configuration.ClientId;
            var clientSecret = request.Configuration.ClientSecret;
            var grantType    = "authorization_code";

            // build token url
            var tokenUrl = "https://api.hubapi.com/oauth/v1/token";

            // build form data request
            var formData = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("grant_type", grantType),
                new KeyValuePair <string, string>("client_id", clientId),
                new KeyValuePair <string, string>("client_secret", clientSecret),
                new KeyValuePair <string, string>("redirect_uri", redirectUrl),
                new KeyValuePair <string, string>("code", code)
            };

            var body = new FormUrlEncodedContent(formData);

            // get tokens
            var oAuthState = new OAuthState();

            try
            {
                // var client = _injectedClient;
                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var response = await client.PostAsync(tokenUrl, body);

                response.EnsureSuccessStatusCode();

                var content = JsonConvert.DeserializeObject <TokenResponse>(await response.Content.ReadAsStringAsync());

                oAuthState.AuthToken    = content.AccessToken;
                oAuthState.RefreshToken = content.RefreshToken;
                oAuthState.Config       = JsonConvert.SerializeObject(new OAuthConfig
                {
                    RedirectUri = redirectUrl
                });

                if (String.IsNullOrEmpty(oAuthState.RefreshToken))
                {
                    throw new Exception("Response did not contain a refresh token");
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
                throw;
            }

            // return oauth state json
            var oAuthResponse = new CompleteOAuthFlowResponse
            {
                OauthStateJson = JsonConvert.SerializeObject(oAuthState)
            };

            Logger.Info("Got Auth Token and Refresh Token");

            return(oAuthResponse);
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: bevacqua/BridgeStack
 private static void GetOAuthRoute()
 {
     var state = new OAuthState();
     state.Add("example", "value");
     state.Add("another", "string");
     string value = oauth.GetExplicitOAuthApprovalUri(new OAuthScope
     {
         ReadInbox = true,
         NoExpiry = true
     }, state);
     Console.WriteLine(value);
 }
コード例 #15
0
 public void SaveState(string key, OAuthState state)
 {
     cache.Set(BuildCacheKey(key), state, TimeSpan.FromMinutes(15));
 }
コード例 #16
0
        /// <summary>
        /// Gets auth token and refresh tokens from auth code
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task <CompleteOAuthFlowResponse> CompleteOAuthFlow(CompleteOAuthFlowRequest request,
                                                                                 ServerCallContext context)
        {
            Logger.SetLogPrefix("complete_oauth");
            Logger.Info("Getting Auth and Refresh Token...");

            // get code from redirect url
            string code;
            var    uri = new Uri(request.RedirectUrl);

            try
            {
                code = HttpUtility.ParseQueryString(uri.Query).Get("code");
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
                throw;
            }

            // token url parameters
            var redirectUrl = String.Format("{0}{1}{2}{3}", uri.Scheme, Uri.SchemeDelimiter, uri.Authority,
                                            uri.AbsolutePath);
            var clientId     = request.Configuration.ClientId;
            var clientSecret = request.Configuration.ClientSecret;
            var grantType    = "authorization_code";

            // build token url
            var tokenUrl = String.Format(
                "https://accounts.zoho.com/oauth/v2/token?code={0}&redirect_uri={1}&client_id={2}&client_secret={3}&grant_type={4}",
                code,
                redirectUrl,
                clientId,
                clientSecret,
                grantType
                );

            // get tokens
            var oAuthState = new OAuthState();

            try
            {
                var response = await _injectedClient.PostAsync(tokenUrl, null);

                response.EnsureSuccessStatusCode();

                var content = JsonConvert.DeserializeObject <TokenResponse>(await response.Content.ReadAsStringAsync());

                oAuthState.AuthToken    = content.access_token;
                oAuthState.RefreshToken = content.refresh_token;

                if (String.IsNullOrEmpty(oAuthState.RefreshToken))
                {
                    throw new Exception("Response did not contain a refresh token");
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
                throw;
            }

            // return oauth state json
            var oAuthResponse = new CompleteOAuthFlowResponse
            {
                OauthStateJson = JsonConvert.SerializeObject(oAuthState)
            };

            Logger.Info("Got Auth Token and Refresh Token");

            return(oAuthResponse);
        }