Пример #1
0
        public string GetAccessToken(string userMailId)
        {
            IZohoPersistenceHandler persistenceHandler = ZohoOAuth.GetPersistenceHandlerInstance();

            ZohoOAuthTokens tokens;

            try
            {
                ZCRMLogger.LogInfo("Retreiving access token..");
                tokens = persistenceHandler.GetOAuthTokens(userMailId);
            }
            catch (Exception e) when(!(e is ZohoOAuthException))
            {
                ZCRMLogger.LogError("Exception while fetching tokens from persistence" + e);
                throw new ZohoOAuthException(e);
            }
            try
            {
                return(tokens.AccessToken);
            }
            catch (ZohoOAuthException)
            {
                ZCRMLogger.LogInfo("Access Token expired, Refreshing Access token");
                tokens = RefreshAccessToken(tokens.RefreshToken, userMailId);
            }
            return(tokens.AccessToken);
        }
Пример #2
0
        public string GenerarGranToken()
        {
            try
            {
                //ServicePointManager.ServerCertificateValidationCallback = ValidateRemoteCertificate;
                WebRequest request = WebRequest.Create(ZohoOAuth.GetLoginZohoURL());
                request.Method = "POST";
                byte[] byteArray = Encoding.UTF8.GetBytes(ZohoOAuth.GetIAMUrl());
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                WebResponse response = request.GetResponse();
                dataStream = response.GetResponseStream();
                StreamReader reader             = new StreamReader(dataStream);
                string       responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();

                return(responseFromServer);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Пример #3
0
        public string GetUserMailIdv2(string accessToken)
        {
            try
            {
                Dictionary <string, string> requestParams = new Dictionary <string, string>();
                HttpClient http = new HttpClient();

                requestParams.Add("client_id", oAuthParams.ClientId);
                requestParams.Add("client_secret", oAuthParams.ClientSecret);
                requestParams.Add("redirect_uri", oAuthParams.RedirectURL);

                JObject JsonObject = new JObject();
                JsonObject.Add(new JProperty("client_id", oAuthParams.ClientId));
                JsonObject.Add(new JProperty("client_secret", oAuthParams.ClientSecret));
                JsonObject.Add(new JProperty("redirect_uri", oAuthParams.RedirectURL));

                StringContent oString = new StringContent(JsonObject.ToString());
                http.DefaultRequestHeaders.Add("authorization", ZohoOAuthConstants.AuthHeaderPrefix + accessToken);

                HttpResponseMessage response = http.PostAsync(ZohoOAuth.GetUserInfoURL(), oString).Result;
                string res = response.Content.ReadAsStringAsync().Result;

                return(res);
            }
            catch (Exception) { throw; }
        }
Пример #4
0
 //TODO: Create ZohoOAuthException class and change the throw exception class;
 public ZohoOAuthTokens RefreshAccessToken(string refreshToken, string userMailId)
 {
     if (refreshToken == null)
     {
         throw new ZohoOAuthException("Refresh token is not provided");
     }
     try
     {
         ZohoHTTPConnector conn = GetZohoConnector(ZohoOAuth.GetRefreshTokenURL());
         conn.AddParam(ZohoOAuthConstants.GRANT_TYPE, ZohoOAuthConstants.REFRESH_TOKEN);
         conn.AddParam(ZohoOAuthConstants.REFRESH_TOKEN, refreshToken);
         string  response     = conn.Post();
         JObject responseJSON = JObject.Parse(response);
         if (responseJSON.ContainsKey(ZohoOAuthConstants.ACCESS_TOKEN))
         {
             ZohoOAuthTokens tokens = GetTokensFromJSON(responseJSON);
             tokens.RefreshToken = refreshToken;
             tokens.UserMaiilId  = userMailId;
             ZohoOAuth.GetPersistenceHandlerInstance().SaveOAuthTokens(tokens);
             return(tokens);
         }
         throw new ZohoOAuthException("Exception while fetching access tokens from Refresh Token" + response);
     }
     catch (WebException e)
     {
         ZCRMLogger.LogError(e);
         throw new ZohoOAuthException(e);
     }
 }
Пример #5
0
        public static void Initialize(bool initOAuth,
                                      Stream configStream,
                                      Dictionary <string, string> configData)
        {
            Assembly assembly = Assembly.GetAssembly(typeof(ZCRMConfigUtil));

            //ConfigProperties =
            //    CommonUtil.GetFileAsDict(
            //        assembly.GetManifestResourceStream(assembly.GetName().Name + ".Resources.configuration.txt"));


            // Stream st = new Stream;

            ConfigProperties =
                CommonUtil.GetFileAsDict(File.Open(@"D:\Github\configuration.txt", FileMode.Open));



            if (configStream == null && configData == null)
            {
                Dictionary <string, string> keyValuePairs = CommonUtil.GetConfigFileAsDict("zcrm_configuration");

                foreach (KeyValuePair <string, string> keyValues in keyValuePairs)
                {
                    ConfigProperties[keyValues.Key] = keyValues.Value;
                }
            }
            if (configStream != null)
            {
                configData   = CommonUtil.GetFileAsDict(configStream);
                configStream = null;
            }
            if (configData != null)
            {
                AddConfigurationData(configData);
            }
            ZCRMLogger.Init();

            if (initOAuth)
            {
                HandleAuthentication = true;
                try
                {
                    ZohoOAuth.Initialize(ConfigProperties.ContainsKey(APIConstants.DOMAIN_SUFFIX) ? (string)ConfigProperties[APIConstants.DOMAIN_SUFFIX] : null, configData);
                    if (ConfigProperties.ContainsKey(APIConstants.DOMAIN_SUFFIX))
                    {
                        SetAPIBaseUrl(ConfigProperties[APIConstants.DOMAIN_SUFFIX]);
                    }
                }
                catch (Exception e)
                {
                    throw new ZCRMException(e);
                }
            }
            ZCRMLogger.LogInfo("C# Client Library Configuration Properties : " + CommonUtil.DictToString(ConfigProperties));
        }
Пример #6
0
        public void GetToken()
        {
            //ZCRMRestClient.Initialize(Dictionary.config);
            //ZohoOAuthClient client = ZohoOAuthClient.GetInstance();

            ZohoOAuthClient.Initialize();
            ZCRMRestClient.Initialize(null);
            ZohoOAuthClient client = ZohoOAuthClient.GetInstance();

            //ZohoOAuthParams param = new ZohoOAuthParams();
            //param.ClientId = "1000.BT8QS94IIA8278417LUKT1DE7XXBFH";
            //param.ClientSecret = "e319f52223bc374d77c65ab410587593cf3ae7e20c";
            //param.RedirectURL = "https://zohoapis.zoho.com/";
            //param.AccessType = "code";
            //param.Scopes = "ZohoCRM.modules.all";
            ///ZohoOAuthClient client = new ZohoOAuthClient(param);

            string grantToken = "1000.a25f043b256bcdcab5804a0cec61c684.ba747fb495a81327a9d78b0e2a1d052f";

            // ZohoOAuthTokens tokens = client.GenerateAccessToken(grantToken);

            //string accessToken = tokens.AccessToken;
            //string refreshToken = tokens.RefreshToken;


            try
            {
                var conn = client.GetZohoConnector(ZohoOAuth.GetTokenURL());
                conn.AddParam(ZohoOAuthConstants.GRANT_TYPE, ZohoOAuthConstants.GRANT_TYPE_AUTH_CODE);
                conn.AddParam(ZohoOAuthConstants.CODE, grantToken);
                string response = conn.Post();

                string v = string.Empty;

                JObject responseJSON = JObject.Parse(response);

                //if (responseJSON.ContainsKey(ZohoOAuthConstants.ACCESS_TOKEN))
                //{
                //    ZohoOAuthTokens tokens = client.GetTokensFromJSON(responseJSON);
                //    tokens.UserMaiilId = client.GetUserMailId(tokens.AccessToken);
                //    ZohoOAuth.GetPersistenceHandlerInstance().SaveOAuthTokens(tokens);

                //    string accessToken = tokens.AccessToken;
                //    string refreshToken = tokens.RefreshToken;
                //    //return tokens;
                //}
                //throw new ZohoOAuthException("Exception while fetching Access Token from grant token" + response);
            }
            catch (WebException e)
            {
                ZCRMLogger.LogError(e);
                throw new ZohoOAuthException(e);
            }
        }
Пример #7
0
        /// <summary>
        /// To get access token from grantToken.
        /// </summary>
        /// <returns>ZohoOAuthTokens class instance.</returns>
        /// <param name="grantToken">Grant token (String) of the oauth client</param>
        public ZohoOAuthTokens GenerateAccessToken(string grantToken)
        {
            if (grantToken == null || grantToken.Length == 0)
            {
                MessageBox.Show("Grant Type is not provided");
                new ZohoOAuthException("Grant Type is not provided");
                return(null);
            }

            try
            {
                var conn = GetZohoConnector(ZohoOAuth.GetTokenURL());
                conn.AddParam(ZohoOAuthConstants.GRANT_TYPE, ZohoOAuthConstants.GRANT_TYPE_AUTH_CODE);
                conn.AddParam(ZohoOAuthConstants.CODE, grantToken);
                string response = conn.Post();

                JObject responseJSON = JObject.Parse(response);

                if (responseJSON.ContainsKey(ZohoOAuthConstants.ACCESS_TOKEN))
                {
                    ZohoOAuthTokens tokens = GetTokensFromJSON(responseJSON);
                    //tokens.UserMaiilId = GetUserMailId(tokens.AccessToken);
                    //tokens.UserMaiilId = GetUserMailIdv2(tokens.AccessToken);
                    tokens.UserMaiilId = ZCRMConfigUtil.ConfigProperties["currentUserEmail"];
                    ZohoOAuth.GetPersistenceHandlerInstance().SaveOAuthTokens(tokens);
                    return(tokens);
                }

                MessageBox.Show("Exception while fetching Access Token from grant token" + response);
                new ZohoOAuthException("Exception while fetching Access Token from grant token" + response);
                return(null);
            }
            catch (WebException e)
            {
                ZCRMLogger.LogError(e);
                throw new ZohoOAuthException(e);
            }
        }
Пример #8
0
        //TODO: the method throws three exceptions and check for null exception on access_token.
        public string GetUserMailId(string accessToken)
        {
            try
            {
                ZohoHTTPConnector conn = new ZohoHTTPConnector()
                {
                    Url = ZohoOAuth.GetUserInfoURL()
                };
                //conn.AddHeader("Authorization", ZohoOAuthConstants.AuthHeaderPrefix + accessToken);
                conn.AddHeader("Authorization", ZohoOAuthConstants.Bearer + accessToken);
                string  response     = conn.Get();
                JObject responseJSON = JObject.Parse(response);

                if (response == null)
                {
                    return(null);
                }
                else
                {
                    return(responseJSON["Email"].ToString());
                }
            }
            catch (WebException) { throw; }
        }