Пример #1
0
        public async Task <IUser> CreateActiveUser(string userName, string firstName, string password)
        {
            var options = new CreateUserWithPasswordOptions
            {
                Profile = new UserProfile
                {
                    Email        = userName,
                    Login        = userName,
                    FirstName    = firstName,
                    LastName     = "Lastname",
                    PrimaryPhone = "2065551212",
                },
                Password = password,
                Activate = true,
            };

            return(await _client.Users.CreateUserAsync(options));
        }
Пример #2
0
        private CSEntryChangeResult PutCSEntryChangeAdd(CSEntryChange csentry, ExportContext context)
        {
            AuthenticationProvider provider = new AuthenticationProvider();

            provider.Type = AuthenticationProviderType.Okta;

            UserProfile profile     = new UserProfile();
            bool        suspend     = false;
            string      newPassword = null;

            foreach (AttributeChange change in csentry.AttributeChanges)
            {
                if (change.Name == "provider.type")
                {
                    provider.Type = new AuthenticationProviderType(change.GetValueAdd <string>());
                    logger.Info($"Set {change.Name} to {provider.Type ?? "<null>"}");
                }
                else if (change.Name == "provider.name")
                {
                    provider.Name = change.GetValueAdd <string>();
                    logger.Info($"Set {change.Name} to {provider.Name ?? "<null>"}");
                }
                else if (change.Name == "suspended")
                {
                    suspend = change.GetValueAdd <bool>();
                }
                else if (change.Name == "export_password")
                {
                    newPassword = change.GetValueAdd <string>();
                }
                else
                {
                    if (change.IsMultiValued)
                    {
                        profile[change.Name] = change.GetValueAdds <object>();
                    }
                    else
                    {
                        profile[change.Name] = change.GetValueAdd <object>();
                        logger.Info($"Set {change.Name} to {profile[change.Name] ?? "<null>"}");
                    }
                }
            }

            IOktaClient client = ((OktaConnectionContext)context.ConnectionContext).Client;
            IUser       result;

            if (newPassword != null)
            {
                CreateUserWithPasswordOptions options = new CreateUserWithPasswordOptions()
                {
                    Password = newPassword,
                    Activate = false,
                    Profile  = profile
                };

                result = AsyncHelper.RunSync(client.Users.CreateUserAsync(options, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
            }
            else
            {
                CreateUserWithProviderOptions options = new CreateUserWithProviderOptions()
                {
                    Profile      = profile,
                    ProviderName = provider.Name,
                    ProviderType = provider.Type,
                    Activate     = false
                };

                result = AsyncHelper.RunSync(client.Users.CreateUserAsync(options, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
            }

            if (context.ConfigParameters[ConfigParameterNames.ActivateNewUsers].Value == "1")
            {
                bool sendEmail = context.ConfigParameters[ConfigParameterNames.SendActivationEmailToNewUsers].Value == "1";
                AsyncHelper.RunSync(client.Users.ActivateUserAsync(result.Id, sendEmail, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
            }

            if (suspend)
            {
                AsyncHelper.RunSync(result.SuspendAsync(context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
            }

            List <AttributeChange> anchorChanges = new List <AttributeChange>();

            anchorChanges.Add(AttributeChange.CreateAttributeAdd("id", result.Id));

            return(CSEntryChangeResult.Create(csentry.Identifier, anchorChanges, MAExportError.Success));
        }
Пример #3
0
        public async Task <Entities.Users.User> RegisterUserAsync(RegisterUserRequest request)
        {
            IUser oktaUser = null;

            try
            {
                var oktaUserRequest = new CreateUserWithPasswordOptions
                {
                    Activate = true,
                    Profile  = new UserProfile
                    {
                        FirstName = request.FirstName,
                        LastName  = request.LastName,
                        Email     = request.Email,
                        Login     = request.Email
                    },
                    Password = request.Password
                };

                oktaUser = await _oktaClient.Users.CreateUserAsync(oktaUserRequest);

                _logger.LogDebug($"Registered user {request.Email} with Okta. Okta ID: {oktaUser.Id}");

                if (!string.IsNullOrEmpty(_oktaConfig.AppGroupName))
                {
                    var appGroup = await _oktaClient.Groups.FirstOrDefaultAsync(x => x.Profile.Name == _oktaConfig.AppGroupName);

                    if (appGroup != null)
                    {
                        await _oktaClient.Groups.AddUserToGroupAsync(appGroup.Id, oktaUser.Id);
                    }

                    _logger.LogDebug($"Added user {request.Email} to Okta group {_oktaConfig.AppGroupName}");
                }
            }
            catch (OktaApiException oktaEx)
            {
                _logger.LogError(oktaEx, $"Error creating user {request.Email} in Okta. Error Code: {oktaEx.ErrorCode}. Summary: {oktaEx.ErrorSummary}");

                // TODO: throw a more friendly error message
                throw new Exception(oktaEx.ErrorSummary, oktaEx);
            }

            try
            {
                var user = new Entities.Users.User
                {
                    SubjectId    = oktaUser.Id,
                    EmailAddress = request.Email,
                    FirstName    = request.FirstName,
                    LastName     = request.LastName,
                    RegisteredOn = DateTime.UtcNow
                };

                await CreateUserAsync(user);

                _logger.LogDebug($"Registered user {request.Email}");

                return(user);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error registering user {request.Email}");
                throw ex;
            }
        }
Пример #4
0
        public IActionResult ValidateUser(string psw, string username)
        {
            string temp = psw;
            PswMigrationResponse pswMigrationRsp = new PswMigrationResponse();

            Okta.Sdk.IUser oktaUser = null;

            var client = new OktaClient(new OktaClientConfiguration
            {
                OktaDomain = _config.GetValue <string>("OktaWeb:OktaDomain"),
                Token      = _config.GetValue <string>("OktaWeb:ApiToken")
            });

            //use received username and password to bind with LDAP
            //if password is valid, set password in Okta
            try
            {
                //check username in Okta and password status
                oktaUser = (Okta.Sdk.User)client.Users.GetUserAsync(username).Result;
            }
            catch (OktaApiException ex)
            {
                //trap error, handle User is null
                var test = ex.ErrorCode;
            }
            catch (Exception e)
            {
                //trap error, handle User is null
                OktaApiException myExp = (OktaApiException)e.InnerException;
                var myErr = myExp.ErrorCode;
            }

            if (oktaUser != null)
            {
                //if user password already set, no furhter processing
                if (oktaUser.Profile["IsPasswordInOkta"] == null || oktaUser.Profile["IsPasswordInOkta"].ToString() == "false")
                {
                    //check user credentials in LDAP
                    bool rspIsAuthenticated = _credAuthentication.IsAuthenticated(username, psw, _ldapServiceModel);

                    if (rspIsAuthenticated)
                    {
                        //set password in Okta
                        Okta.Sdk.PasswordCredential setPassword = new Okta.Sdk.PasswordCredential();
                        setPassword.Value = psw;

                        oktaUser.Credentials.Password        = setPassword;
                        oktaUser.Profile["IsPasswordInOkta"] = "true";

                        Okta.Sdk.IUser rspPartialUpdate = oktaUser.UpdateAsync().Result;

                        if (rspPartialUpdate != null)
                        {
                            if (rspPartialUpdate.PasswordChanged != null)
                            {
                                pswMigrationRsp.status           = "set password in Okta successful";
                                pswMigrationRsp.isPasswordInOkta = "true";
                            }
                            else
                            {
                                pswMigrationRsp.status           = "set password in Okta failed";
                                pswMigrationRsp.isPasswordInOkta = "false";
                            }
                        }
                        else
                        {
                            pswMigrationRsp.status           = "set password in Okta failed";
                            pswMigrationRsp.isPasswordInOkta = "false";
                        }
                    }
                    else
                    {
                        //arrive here is user creds not validated in Ldap
                        pswMigrationRsp.status           = "LDAP validation failed";
                        pswMigrationRsp.isPasswordInOkta = "false";
                    }
                }
                else
                {
                    //no work required
                    pswMigrationRsp.status           = oktaUser.Status;
                    pswMigrationRsp.isPasswordInOkta = "true";
                }
                //build response
                pswMigrationRsp.oktaId = oktaUser.Id;
                pswMigrationRsp.login  = oktaUser.Profile.Login;
            }
            else
            {
                //arrive here if user not found in Okta
                //check user credentials and get profile from LDAP
                //Okta.Sdk.IUser rspOktaUser = null;
                CustomUser rspCustomUser = _credAuthentication.IsCreated(username, psw, _ldapServiceModel);
                if (rspCustomUser != null)
                {
                    //create Okta user with password
                    //dont auto activate, sincewe dont want email
                    CreateUserWithPasswordOptions newUserOptions = new CreateUserWithPasswordOptions
                    {
                        // User profile object
                        Profile = new UserProfile
                        {
                            Login     = rspCustomUser.Email,
                            FirstName = rspCustomUser.FirstName,
                            LastName  = rspCustomUser.LastName,
                            Email     = rspCustomUser.Email
                        },
                        Password = psw,
                        Activate = false,
                    };
                    newUserOptions.Profile["IsPasswordInOkta"] = "true";
                    Okta.Sdk.IUser rspAddCustomUser = client.Users.CreateUserAsync(newUserOptions).Result;


                    if (rspAddCustomUser != null)
                    {
                        var rspActivate = rspAddCustomUser.ActivateAsync(sendEmail: false).Result;
                        if (rspActivate != null)
                        {
                            pswMigrationRsp.oktaId           = rspAddCustomUser.Id;
                            pswMigrationRsp.login            = rspAddCustomUser.Profile.Login;
                            pswMigrationRsp.status           = "Created in Okta";
                            pswMigrationRsp.isPasswordInOkta = "true";
                        }
                        else
                        {
                            pswMigrationRsp.oktaId           = rspAddCustomUser.Id;
                            pswMigrationRsp.login            = rspAddCustomUser.Profile.Login;
                            pswMigrationRsp.status           = "User NOT ACTIVE in Okta";
                            pswMigrationRsp.isPasswordInOkta = "unknown";
                        }
                    }
                    else
                    {
                        pswMigrationRsp.oktaId           = "none";
                        pswMigrationRsp.login            = "******";
                        pswMigrationRsp.status           = "User NOT Created in Okta";
                        pswMigrationRsp.isPasswordInOkta = "false";
                    }
                }
                else
                {
                    pswMigrationRsp.oktaId           = "none";
                    pswMigrationRsp.login            = "******";
                    pswMigrationRsp.status           = "User NOT found in External Source";
                    pswMigrationRsp.isPasswordInOkta = "false";
                }
            }

            return(Content(content: JsonConvert.SerializeObject(pswMigrationRsp), contentType: "application/json"));


            // return this.Ok("Web Api unprotected endpoint, SUCCESS");
        }