public bool SetupUserInOkta(string username, string password)
        {
            bool       returnCode = false;
            CustomUser customUser = GetCustomUser(username);

            if (customUser != null)
            {
                // activate the user if not already activated - don't send activation email
                if (string.Equals(customUser.Status, "STAGED", StringComparison.InvariantCultureIgnoreCase))
                {
                    _usersClient.Activate(customUser.Id, false);
                }

                // Update user's password
                _usersClient.SetPassword(customUser, password);
                returnCode = true;
            }

            return(returnCode);
        }
Пример #2
0
        //public PagedResults<CustomUser> ListCustomUsersWithQuery(string query, Uri nextPage = null)
        //{
        //    PagedResults<User> oktaUserList = null;

        //    List<CustomUser> customUserList = new List<CustomUser>();
        //    CustomUser customUser = null;
        //    try
        //    {
        //        oktaUserList = _usersClient.GetList(nextPage, query: query, pageSize: 200);

        //        foreach (var user in oktaUserList.Results)
        //        {
        //            customUser = new CustomUser(user);
        //            customUser.extProfile = new CustomUserProfile();

        //            List<string> customAttributes = user.Profile.GetUnmappedPropertyNames();
        //            foreach (var item in customAttributes)
        //            {

        //                PropertyInfo tempProp = customUser.extProfile.GetType().GetProperty(item);
        //                if (tempProp != null)
        //                {
        //                    object myValue = user.Profile.GetProperty(item);
        //                    if (tempProp.CanWrite)
        //                    {
        //                        tempProp.SetValue(customUser.extProfile, myValue, null);
        //                    }
        //                }
        //                else
        //                {
        //                    _logger.Debug("unmapped okta attribute " + item + " is not defined as an extention");
        //                }

        //            }
        //        }


        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.Error(string.Format("Error searching for Okta user in Okta. Okta username: {0}.", query), ex);
        //    }
        //    PagedResults<CustomUser> pagedCustomUserList = new PagedResults<CustomUser>(customUserList);
        //    return pagedCustomUserList;
        //}


        //public PagedResults<CustomUser> ListCustomUsersWithFilter(string filter, Uri nextPage = null)
        //{
        //    FilterBuilder filterBuilder = new FilterBuilder(filter);

        //    PagedResults<User> oktaUserList = null;

        //    List<CustomUser> customUserList = new List<CustomUser>();
        //    CustomUser customUser = null;
        //    try
        //    {
        //        oktaUserList = _usersClient.GetList(nextPage: nextPage, filter: filterBuilder, searchType: SearchType.Filter, pageSize: 200);

        //        foreach (var user in oktaUserList.Results)
        //        {
        //            customUser = new CustomUser(user);
        //            customUser.extProfile = new CustomUserProfile();

        //            List<string> customAttributes = user.Profile.GetUnmappedPropertyNames();
        //            foreach (var item in customAttributes)
        //            {

        //                PropertyInfo tempProp = customUser.extProfile.GetType().GetProperty(item);
        //                if (tempProp != null)
        //                {
        //                    object myValue = user.Profile.GetProperty(item);
        //                    if (tempProp.CanWrite)
        //                    {
        //                        tempProp.SetValue(customUser.extProfile, myValue, null);
        //                    }
        //                }
        //                else
        //                {
        //                    _logger.Debug("unmapped okta attribute " + item + " is not defined as an extention");
        //                }

        //            }
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.Error(string.Format("Error searching for Okta user in Okta. Okta username: {0}.", filter), ex);
        //    }
        //    PagedResults<CustomUser> pagedCustomUserList = new PagedResults<CustomUser>(customUserList);
        //    return pagedCustomUserList;
        //}

        //public PagedResults<CustomUser> ListCustomUsersWithSearch(string searchType, string criteria, Uri nextPage = null)
        //{

        //    string encodedfilter = null;
        //    string stringFilter = criteria.ToString();
        //    encodedfilter = HttpUtility.UrlPathEncode(stringFilter);
        //    FilterBuilder filterBuilder = new FilterBuilder(encodedfilter);
        //    PagedResults<User> oktaUserList = null;
        //    List<CustomUser> customUserList = new List<CustomUser>();
        //    CustomUser customUser = null;
        //    try
        //    {
        //        if (searchType == "query")
        //        {
        //            oktaUserList = _usersClient.GetList(nextPage, query: criteria, pageSize: 200);
        //        }
        //        else if (searchType == "search")
        //        {
        //            oktaUserList = _usersClient.GetList(nextPage: nextPage, filter: filterBuilder, searchType: SearchType.ElasticSearch, pageSize: 200);
        //        }
        //        else if (searchType == "filter")
        //        {
        //            oktaUserList = _usersClient.GetList(nextPage: nextPage, filter: filterBuilder, searchType: SearchType.Filter, pageSize: 200);
        //        }



        //        foreach (var user in oktaUserList.Results)
        //        {
        //            customUser = new CustomUser(user);
        //            customUser.extProfile = new CustomUserProfile();

        //            List<string> customAttributes = user.Profile.GetUnmappedPropertyNames();
        //            foreach (var item in customAttributes)
        //            {

        //                PropertyInfo tempProp = customUser.extProfile.GetType().GetProperty(item);
        //                if (tempProp != null)
        //                {
        //                    object myValue = user.Profile.GetProperty(item);
        //                    if (tempProp.CanWrite)
        //                    {
        //                        tempProp.SetValue(customUser.extProfile, myValue, null);
        //                    }
        //                }
        //                else
        //                {
        //                    _logger.Debug("unmapped okta attribute " + item + " is not defined as an extention");
        //                }
        //                customUserList.Add(customUser);
        //            }
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.Error(string.Format("Error searching for Okta user in Okta. Okta username: {0}.", criteria), ex);
        //    }
        //    PagedResults<CustomUser> pagedCustomUserList = new PagedResults<CustomUser>(customUserList);
        //    pagedCustomUserList.NextPage = oktaUserList.NextPage;
        //    pagedCustomUserList.PrevPage = oktaUserList.PrevPage;
        //    //pagedCustomUserList.RequestUri = oktaUserList.RequestUri;
        //    return pagedCustomUserList;


        //}

        //public CustomPagedResults<User> SearchCustomUsers(StringBuilder searchCriteria, Uri myUri = null)
        //{
        //    _logger.Debug("Search User criteria " + searchCriteria.ToString());
        //    //search user
        //    //users?search=
        //    //full profile including custom
        //    //id,status,created,activated,statusChanged,lastUpdated


        //    string encodedUrl = null;

        //    string stringFilter = searchCriteria.ToString();

        //    encodedUrl = HttpUtility.UrlPathEncode(stringFilter);

        //    string apiEndPoint = _orgUrl + Constants.EndpointV1 + Constants.UsersEndpoint + "?search=" + encodedUrl;
        //    Uri apiEndPointUri = new Uri(apiEndPoint);

        //    string httpStatus = null;
        //    //// CustomUser customUser = new CustomUser();
        //    ////customUser.profile = new Profile();
        //    //List<CustomUser> listCustomUser = new List<CustomUser>();
        //    List<User> listCustomUser = new List<User>();
        //    //RestClient client;
        //    //IRestResponse<List<CustomUser>> response;

        //    try
        //    {
        //        //if (myUri == null)
        //        //{
        //        //    //no Uri provided build it
        //        //    client = new RestClient(MvcApplication.apiUrl + "/api/v1/users?search=" + encodedUrl);
        //        //}
        //        //else
        //        //{
        //        //    //usr uri parameter
        //        //    client = new RestClient(myUri);
        //        //}

        //        //var request = new RestRequest(Method.GET);
        //        //request.AddHeader("Accept", "application/json");
        //        //request.AddHeader("Content-Type", "application/json");
        //        //request.AddHeader("Authorization", "SSWS " + MvcApplication.apiToken);
        //        //response = client.Execute<List<CustomUser>>(request);
        //        //httpStatus = response.StatusDescription;

        //        HttpResponseMessage response = _oktaClient.BaseClient.Get(apiEndPointUri);
        //        string responseTopContent = response.ToString();
        //        var index = responseTopContent.IndexOf(",", 20);
        //        var rspStatus = responseTopContent.Substring(0, index);
        //        string content = response.Content.ReadAsStringAsync().Result;
        //        _logger.Debug("response " + rspStatus + " content " + content);
        //        //listCustomUser = Utils.Deserialize<List<CustomUser>>(response);
        //        listCustomUser = Utils.Deserialize<List<User>>(response);


        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.Error(ex.ToString());
        //        return null;
        //    }//end catch
        //if (httpStatus == "OK")
        //{
        //    //customUser = response.Data[0];
        //    listCustomUser = response.Data;
        // CustomPagedResults<CustomUser> customPagedResults = new CustomPagedResults<CustomUser>(listCustomUser);
        // CustomPagedResults<User> customPagedResults = new CustomPagedResults<User>(listCustomUser);
        //    //customPagedResults.Results = response.Data;
        //    customPagedResults.count = listCustomUser.Count;
        //    string self = null;
        //    string next = null;
        //    var headerList = response.Headers.ToList();
        //    string link = headerList.Find(x => x.Name == "Link").Value.ToString();


        //    int linkIndex = link.IndexOf(",");
        //    if (linkIndex > 0)
        //    {
        //        self = link.Substring(0, linkIndex);
        //    }
        //    else
        //    {
        //        self = link;
        //    }
        //    if (self.Contains("self"))
        //    {
        //        _logger.Debug("received selfLink: " + self);
        //        int selfIndex = self.IndexOf(">");
        //        string selfMod = self.Substring(1, selfIndex - 1);
        //        customPagedResults.RequestUri = new Uri(selfMod);
        //    }
        //    else
        //    {
        //        _logger.Error("Self link not found");
        //    }

        //    if (linkIndex > 0)
        //    {
        //        next = link.Substring(linkIndex + 1);
        //        if (next.Contains("next"))
        //        {
        //            _logger.Debug("received nextLink: " + next);
        //            int nextIndex = next.IndexOf(">");
        //            string nextMod = next.Substring(1, nextIndex - 1);
        //            customPagedResults.NextPage = new Uri(nextMod);
        //        }
        //        else
        //        {
        //            _logger.Debug("Next link not present");
        //        }
        //    }
        //    else
        //    {
        //        _logger.Debug("Next link not present");
        //    }

        // return customPagedResults;

        //}
        //else
        //{
        //    _logger.Error("Error in http call status:" + httpStatus);
        //    return null;
        //}
        // }



        //public bool SetupUserInOkta(string username, string password)
        //{
        //    bool success = false;
        //    CustomUser myUser = GetCustomUser(username);
        //    if (myUser != null)
        //    {
        //        // activate the user if not already activated - don't send activation email
        //        if (string.Equals(myUser.Status, "STAGED", StringComparison.InvariantCultureIgnoreCase))
        //        {
        //            _usersClient.Activate(myUser.Id, false);
        //        }

        //        // Update user's password
        //        _usersClient.SetPassword(myUser, password);
        //        success = true;
        //    }

        //    return success;
        //}

        public bool ActivateUser(string oktaId)
        {
            bool success = false;

            try
            {
                _usersClient.Activate(oktaId, false);
                success = true;
            }
            catch (Exception ex)
            {
                _logger.Error("Error activating user. {0}", ex);
            }

            return(success);
        }
Пример #3
0
        public ActionResult VerifyActivate(string recoveryToken, string oktaId)
        {
            logger.Debug("VerifyActivate ");

            if (string.IsNullOrEmpty(recoveryToken) && TempData["recoveryToken"] != null)
            {
                recoveryToken = TempData["recoveryToken"].ToString();
            }

            //set parameters
            string relayState = Request["relayState"];

            if (string.IsNullOrEmpty(relayState) && Request.QueryString["RelayState"] != null)
            {
                relayState = Request.QueryString["RelayState"];
            }
            else if (string.IsNullOrEmpty(relayState) && TempData["relayState"] != null)
            {
                relayState = (string)TempData["relayState"];
            }
            TempData["relayState"] = relayState;
            string stateToken = Request["stateToken"];

            if (string.IsNullOrEmpty(stateToken) && TempData["stateToken"] != null)
            {
                stateToken = TempData["stateToken"].ToString();
            }
            TempData["stateToken"] = stateToken;

            string userName = Request["userName"];

            if (string.IsNullOrEmpty(userName) && TempData["userName"] != null)
            {
                userName = TempData["userName"].ToString();
            }
            TempData["userName"] = userName;



            //TempData["helpLink"] = MvcApplication.helpLink;
            string tokenFailedErrorMessage = "We could not activate your account at this time. Please try clicking the link in your email again " +
                                             "or contact the service center via the information at the bottom of the page.";

            //get UserClient based on Org credentials
            OktaClient  oktaClient  = new OktaClient(MvcApplication.apiToken, MvcApplication.apiUrl);
            UsersClient usersClient = oktaClient.GetUsersClient();

            //Validate Token from branded email response link
            //get user profile data
            //compare with received token
            if (!string.IsNullOrEmpty(recoveryToken) && !string.IsNullOrEmpty(oktaId))
            {
                //validate token
                //get custom profile for user
                User       oktaBaseUser = new Okta.Core.Models.User();
                CustomUser customUser   = new CustomUser(oktaBaseUser);
                customUser = oktaUserMgmt.GetCustomUser(oktaId);
                if (customUser.Status != "STAGED")
                {
                    //if it doesnt work out return to beginning
                    logger.Error("Token validation is not appropriate for current user state " + customUser.Status);
                    TempData["errMessage"] = tokenFailedErrorMessage;
                    return(RedirectToAction("Index", "Home"));
                }
                if (string.IsNullOrEmpty(customUser.Profile.activation_passCode) || string.IsNullOrEmpty(customUser.Profile.activation_setDate))
                {
                    logger.Error("Token validation information is not available");
                    TempData["errMessage"] = tokenFailedErrorMessage;
                    return(RedirectToAction("Index", "Home"));
                }


                //this is a one time token, so if profile received reset the data.
                string activation_passCode = customUser.Profile.activation_passCode;
                string activation_setDate  = customUser.Profile.activation_setDate;
                customUser.Profile.activation_passCode = "";
                customUser.Profile.activation_setDate  = "";

                bool rspSetCustomUserProfile = oktaUserMgmt.UpdateCustomUserAttributesOnly(customUser);
                if (!rspSetCustomUserProfile)
                {
                    logger.Error("Unable to Set User Custom Profile to reset activation passCode: " + customUser.Profile.Email);
                    TempData["errMessage"] = tokenFailedErrorMessage;
                    return(RedirectToAction("Index", "Home"));
                }

                //compare to passed in token
                //Get current time
                DateTime currentTime = DateTime.Now;
                DateTime setTime     = DateTime.Parse(activation_setDate);
                //Get the difference in Minutes between the set time and Current Time.
                TimeSpan timeSpan   = currentTime.Subtract(setTime);
                long     myInterval = Convert.ToInt32(timeSpan.TotalHours);
                long     authExpiry = Convert.ToInt32(appSettings["custom.ActivationExpire_hours"]);
                //check received passcode matches what was saved in storage app attribute

                if (activation_passCode == recoveryToken)
                {
                    //check for expired activation code
                    if (authExpiry > myInterval)
                    {
                        //continue to set password
                        User oktaUser = new User();
                        oktaUser.Id = oktaId;

                        try
                        {
                            //transistion user accout from STAGED to PROVISIONED
                            var rspUri = usersClient.Activate(oktaUser, sendEmail: false);
                            //rsp is email activation link for embedded workflow
                            //this cannot be branded so we are setting password directly
                        }
                        catch (OktaException ex)
                        {
                            if (ex.ErrorCode == "E0000001")
                            {
                                logger.Error("Api Valiadation Failed: " + userName);
                            }
                            else
                            {
                                logger.Error(userName + " = " + ex.ErrorCode + ":" + ex.ErrorSummary);
                                // generic failure
                            }
                            TempData["errMessage"] = tokenFailedErrorMessage;
                            return(RedirectToAction("Index", "Home"));
                        }//end catch

                        logger.Debug("Token Validated Successfully proceed to create password");
                        return(RedirectToAction("GetPassword"));
                    }
                    else
                    {
                        logger.Debug("Token is correct, but has exceeded time limit " + appSettings["custom.ActivationExpire_hours"] + " hours");
                        TempData["errMessage"] = tokenFailedErrorMessage;
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    logger.Error("Cannot Validate Token: " + recoveryToken + " locator: " + oktaId);
                    TempData["errMessage"] = tokenFailedErrorMessage;
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                //if it doesnt work out return to beginning
                logger.Error("Cannot Validate Token: " + recoveryToken + " locator: " + oktaId);
                TempData["errMessage"] = tokenFailedErrorMessage;
                return(RedirectToAction("Index", "Home"));
            }
        }