Beispiel #1
0
        public async Task GetAccessToken()
        {
            AuthTokenInfo access_tokenInfo = null;

            using (HttpClient hc = new HttpClient())
            {
                hc.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Basic {_authorizarionToken}");
                hc.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

                Dictionary <string, string> dc = new Dictionary <string, string>();
                dc.Add("grant_type", "client_credentials");

                FormUrlEncodedContent content = new FormUrlEncodedContent(dc);

                HttpResponseMessage responseMessage = await hc.PostAsync(_uritoken, content);

                string jsonMessage = await responseMessage.Content.ReadAsStringAsync();

                if (responseMessage.IsSuccessStatusCode)
                {
                    access_tokenInfo = JsonConvert.DeserializeObject <AuthTokenInfo>(jsonMessage);
                }
                else
                {
                    throw new Exception(jsonMessage);
                }
            }

            _token = access_tokenInfo?.AccessToken;
        }
Beispiel #2
0
        public RESTReplyData user_tokens(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info

            if (pReq.Queries.TryGetValue("for_domain_server", out string oForDomainServer))
            {
                if (Boolean.Parse(oForDomainServer))
                {
                    // Getting a token for a domain server
                    if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity oAccount))
                    {
                        AuthTokenInfo token = oAccount.CreateAccessToken(AuthTokenInfo.ScopeCode.domain);
                        // The domain/account association is permenant... expiration is far from now
                        token.TokenExpirationTime = new DateTime(2999, 12, 31);

                        replyData.SetBody($"<center><h2>Your domain's access token is: {token.Token}</h2></center>");
                        replyData.MIMEType = "text/html";
                    }
                    else
                    {
                        // If the user is not logged in, go to a page to login and set things up
                        replyData.Status = (int)HttpStatusCode.Found;
                        replyData.CustomOutputHeaders.Add("Location",
                                                          Context.Params.P <string>(AppParams.P_DOMAIN_TOKENGEN_URL));
                        replyData.MIMEType = "text/html";
                    }
                }
            }
            return(replyData);
        }
Beispiel #3
0
        private static async Task <AuthTokenInfo> GetToken()
        {
            var client  = new HttpClient();
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("grant_type", "client_credentials"),
                new KeyValuePair <string, string>("redirect_uri", AppSettings.RedirectUri)
            });

            var basicAuth = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{AppSettings.ClientID}:{AppSettings.ClientSecret}"));

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicAuth);
            var response = await client.PostAsync("https://login.mypurecloud.ie/oauth/token", content);

            var responseContent = await response.Content.ReadAsStringAsync();

            var responseJObj = JObject.Parse(responseContent);

            var expires = responseJObj.GetValue("expires_in").ToString();

            var tokenInfo = new AuthTokenInfo
            {
                AccessToken = responseJObj.GetValue("access_token").ToString(),
                TokenType   = responseJObj.GetValue("token_type").ToString(),
            };

            int expiresValue;

            if (Int32.TryParse(expires, NumberStyles.Integer, CultureInfo.InvariantCulture, out expiresValue))
            {
                tokenInfo.ExpiresIn = expiresValue;
            }

            return(tokenInfo);
        }
Beispiel #4
0
 public bodyTokenInfo(AuthTokenInfo pToken)
 {
     tokenid               = pToken.TokenId;
     token                 = pToken.Token;
     refresh_token         = pToken.RefreshToken;
     token_creation_time   = XmlConvert.ToString(pToken.TokenCreationTime, XmlDateTimeSerializationMode.Utc);
     token_expiration_time = XmlConvert.ToString(pToken.TokenExpirationTime, XmlDateTimeSerializationMode.Utc);
     scope                 = pToken.Scope.ToString();
 }
Beispiel #5
0
 private string OAuthTokenResponseBody(AccountEntity pAccount, AuthTokenInfo pTokenInfo)
 {
     return(JsonConvert.SerializeObject(new bodyLoginReply()
     {
         access_token = pTokenInfo.Token,
         token_type = "Bearer",
         expires_in = (int)(pTokenInfo.TokenExpirationTime - pTokenInfo.TokenCreationTime).TotalSeconds,
         refresh_token = pTokenInfo.RefreshToken,
         scope = pTokenInfo.Scope.ToString(),
         created_at = ((DateTimeOffset)pTokenInfo.TokenCreationTime).ToUnixTimeSeconds(),
         account_id = pAccount.AccountID,
         account_name = pAccount.Username,
         account_type = pAccount.GetAccountType()
     }));
 }
        /// <summary>
        /// Set the ApiClient using Default or ApiClient instance.
        /// </summary>
        /// <param name="apiClient">An instance of ApiClient.</param>
        /// <returns></returns>
        public void setApiClientUsingDefault(ApiClient apiClient = null)
        {
            AuthTokenInfo = new AuthTokenInfo();
            if (apiClient == null)
            {
                if (Default != null && Default.ApiClient == null)
                    Default.ApiClient = new ApiClient(this);

                ApiClient = Default != null ? Default.ApiClient : new ApiClient(this);
            }
            else
            {
                if (Default != null && Default.ApiClient == null)
                    Default.ApiClient = apiClient;

                ApiClient = apiClient;
            }
        }
Beispiel #7
0
        public RESTReplyData user_login(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            // The /oauth/token request doesn't return a regular respBody

            // Should verify that the content-type is "application/x-www-form-urlencoded"
            Dictionary <string, string> reqArgs = Tools.PostBody2Dict(pReq.RequestBody);

            string accessGrantType = reqArgs["grant_type"];

            switch (accessGrantType)
            {
            case "password":
            {
                // There are several types of "password"s passed by Interface:
                // PLAIN PASSWORD
                string userName     = reqArgs["username"];
                string userPassword = reqArgs["password"];

                // STEAM
                // string userPassword = reqArgs["steam_auth_ticket"];

                // OCULUS
                // string userPassword = reqArgs["oculus_nonce"];
                // string userPassword = reqArgs["oculus_id"];

                AuthTokenInfo.ScopeCode userScope = AuthTokenInfo.ScopeCode.owner;
                if (reqArgs.ContainsKey("scope"))
                {
                    try
                    {
                        userScope = Enum.Parse <AuthTokenInfo.ScopeCode>(reqArgs["scope"] ?? "owner");
                    }
                    catch
                    {
                        Context.Log.Error("{0} /oauth/token: unknown scope code: {1}", _logHeader, reqArgs["scope"]);
                        userScope = AuthTokenInfo.ScopeCode.owner;
                    }
                }

                // Context.Log.Debug("{0} Get access token for {1} with password", _logHeader, userName);

                if (Accounts.Instance.TryGetAccountWithUsername(userName, out AccountEntity aAccount))
                {
                    if (Accounts.Instance.ValidPassword(aAccount, userPassword))
                    {
                        Context.Log.Debug("{0} Login of user {1}", _logHeader, userName);

                        AuthTokenInfo authInfo = aAccount.CreateAccessToken(userScope, pReq.SenderKey + ";" + userName);

                        // The response does not follow the usual {status: , data: } form.
                        replyData.SetBody(OAuthTokenResponseBody(aAccount, authInfo));
                    }
                    else
                    {
                        Context.Log.Debug("{0} Login failed for user {1}", _logHeader, userName);
                        // The password doesn't work.
                        replyData.SetBody(OAuthResponseError("Login failed"));
                        replyData.Status = (int)HttpStatusCode.Unauthorized;
                    }
                }
                else
                {
                    Context.Log.Error("{0} Attempt to get token for unknown user {1}. Sender={2}",
                                      _logHeader, userName, pReq.SenderKey);
                    replyData.SetBody(OAuthResponseError("Unknown user"));
                    replyData.Status = (int)HttpStatusCode.BadRequest;
                }
                break;
            }

            case "authorization_code":
            {
                string clientID       = reqArgs["client_id"];
                string clientSecret   = reqArgs["client_secret"];
                string clientAuthCode = reqArgs["code"];
                string redirectURL    = reqArgs["redirect_url"];

                Context.Log.Error("{0} Attempt to login with 'authorization_code'. clientID={1}",
                                  _logHeader, clientID);
                replyData.SetBody(OAuthResponseError("Cannot process 'authorization_code'"));
                replyData.Status = (int)HttpStatusCode.Unauthorized;
                break;
            }

            case "refresh_token":
            {
                string refreshingToken = reqArgs["refresh_token"];
                string userScope       = reqArgs["scope"] ?? "owner";

                if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity aAccount))
                {
                    Context.Log.Debug("{0} Refreshing access token for account {1}", _logHeader, aAccount.AccountID);
                    AuthTokenInfo refreshToken = aAccount.RefreshAccessToken(refreshingToken);
                    if (refreshToken != null)
                    {
                        replyData.SetBody(OAuthTokenResponseBody(aAccount, refreshToken));
                    }
                    else
                    {
                        replyData.SetBody(OAuthResponseError("Cannot refresh"));
                        replyData.Status = (int)HttpStatusCode.BadRequest;
                    }
                }
                else
                {
                    Context.Log.Error("{0} Attempt to refresh token for not logged in user", _logHeader);
                    replyData.SetBody(OAuthResponseError("Unknown user"));
                    replyData.Status = (int)HttpStatusCode.BadRequest;
                }
                break;
            }

            default:
                Context.Log.Error("{0} Attempt to login with unknown grant type. Type={1}",
                                  _logHeader, accessGrantType);
                replyData.SetBody(OAuthResponseError("Unknown grant type: " + accessGrantType));
                replyData.Status = (int)HttpStatusCode.Unauthorized;
                break;
            }

            // Context.Log.Debug("{0} oauth/token replyBody={1}", _logHeader, replyData.Body);
            return(replyData);
        }
Beispiel #8
0
        public RESTReplyData new_scope_token(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();

            if (Sessions.Instance.ShouldBeThrottled(pReq.SenderKey, Sessions.Op.TOKEN_CREATE))
            {
                respBody.RespondFailure("Throttled");
                respBody.Data = new
                {
                    operation = "throttled"
                };
            }
            else
            {
                // Getting a token for a domain server
                if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity oAccount))
                {
                    AuthTokenInfo token = null;

                    string scope = pReq.Queries.ContainsKey("scope") ? pReq.Queries["scope"] : "owner";
                    switch (scope)
                    {
                    case "domain":
                        token = oAccount.CreateAccessToken(AuthTokenInfo.ScopeCode.domain);
                        // The domain/account association lasts longer
                        token.TokenExpirationTime = new DateTime(2999, 12, 31);
                        break;

                    case "owner":
                        token = oAccount.CreateAccessToken(AuthTokenInfo.ScopeCode.owner);
                        break;

                    default:
                        break;
                    }

                    if (token != null)
                    {
                        respBody.Data = new
                        {
                            token                    = token.Token,
                            token_id                 = token.TokenId,
                            refresh_token            = token.RefreshToken,
                            token_expiration_seconds = (int)(token.TokenExpirationTime - token.TokenCreationTime).TotalSeconds,
                            account_name             = oAccount.Username,
                            account_type             = oAccount.GetAccountType(),
                            account_id               = oAccount.AccountID
                        };
                    }
                    else
                    {
                        respBody.RespondFailure("Token could not be generated. Bad scope?");
                    }
                }
                else
                {
                    // Not a known account.
                    respBody.RespondFailure("Unknown requesting account");
                }
            }
            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
        /// <summary>
        /// Initializes a new instance of the Configuration class with different settings
        /// </summary>
        /// <param name="apiClient">Api client</param>
        /// <param name="defaultHeader">Dictionary of default HTTP header</param>
        /// <param name="username">Username</param>
        /// <param name="password">Password</param>
        /// <param name="accessToken">accessToken</param>
        /// <param name="apiKey">Dictionary of API key</param>
        /// <param name="apiKeyPrefix">Dictionary of API key prefix</param>
        /// <param name="tempFolderPath">Temp folder path</param>
        /// <param name="dateTimeFormat">DateTime format string</param>
        /// <param name="timeout">HTTP connection timeout (in milliseconds)</param>
        /// <param name="shouldRefreshAccessToken">ShouldRefreshAccessToken</param>
        /// <param name="refreshTokenWaitTime">Refresh token wait time in seconds</param>
        /// <param name="userAgent">HTTP user agent</param>
        /// <param name="configFilePath">Config file path</param>
        /// <param name="autoReloadConfig">AutoReloadConfig</param>
        public Configuration(ApiClient apiClient = null,
            Dictionary<String, String> defaultHeader = null,
            string username = null,
            string password = null,
            string accessToken = null,
            Dictionary<String, String> apiKey = null,
            Dictionary<String, String> apiKeyPrefix = null,
            string tempFolderPath = null,
            string dateTimeFormat = null,
            int timeout = 100000,
            bool shouldRefreshAccessToken = true,
            int refreshTokenWaitTime = 10,
            string userAgent = "PureCloud SDK/dotnet",
            string configFilePath = null,
            bool autoReloadConfig = true
            )
        {
            setApiClientUsingDefault(apiClient);

            Username = username;
            Password = password;
            AuthTokenInfo = new AuthTokenInfo();
            AccessToken = accessToken;
            UserAgent = userAgent;

            if (defaultHeader != null)
                DefaultHeader = defaultHeader;
            if (apiKey != null)
                ApiKey = apiKey;
            if (apiKeyPrefix != null)
                ApiKeyPrefix = apiKeyPrefix;

            TempFolderPath = tempFolderPath;
            DateTimeFormat = dateTimeFormat;
            Timeout = timeout;
            ShouldRefreshAccessToken = shouldRefreshAccessToken;
            RefreshTokenWaitTime = refreshTokenWaitTime;

            Logger = new Logger();

            if (String.IsNullOrEmpty(configFilePath))
            {
                string homePath = (Environment.OSVersion.Platform == PlatformID.Unix ||
                                Environment.OSVersion.Platform == PlatformID.MacOSX)
                    ? Environment.GetEnvironmentVariable("HOME")
                    : Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
                ConfigFilePath = Path.Combine(homePath, ".genesysclouddotnet", "config");
            }
            else
            {
                ConfigFilePath = configFilePath;
            }

            AutoReloadConfig = autoReloadConfig;

            if (AutoReloadConfig)
            {
                ThreadStart configCheckerRef = new ThreadStart(runConfigChecker);
                Thread configCheckerThread = new Thread(configCheckerRef);
                configCheckerThread.IsBackground = true;
                configCheckerThread.Start();
            }
        }