private static SchemaType GetSchemaTypeGroup(IOktaClient client)
        {
            SchemaType      mmsType      = SchemaType.Create("group", true);
            SchemaAttribute mmsAttribute = SchemaAttribute.CreateAnchorAttribute("id", AttributeType.String, AttributeOperation.ImportOnly);

            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("created", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("lastUpdated", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("lastMembershipUpdated", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("type", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("name", AttributeType.String, AttributeOperation.ImportExport);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("description", AttributeType.String, AttributeOperation.ImportExport);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateMultiValuedAttribute("member", AttributeType.Reference, AttributeOperation.ImportExport);
            mmsType.Attributes.Add(mmsAttribute);

            return(mmsType);
        }
Example #2
0
        private CSEntryChangeResult PutCSEntryChangeAdd(CSEntryChange csentry, ExportContext context)
        {
            CreateGroupOptions options = new CreateGroupOptions();
            IList <string>     members = new List <string>();

            foreach (AttributeChange change in csentry.AttributeChanges)
            {
                if (change.Name == "name")
                {
                    options.Name = change.GetValueAdd <string>();
                }
                else if (change.Name == "description")
                {
                    options.Description = change.GetValueAdd <string>();
                }
                else if (change.Name == "member")
                {
                    members = change.GetValueAdds <string>();
                }
            }

            IOktaClient client = ((OktaConnectionContext)context.ConnectionContext).Client;
            IGroup      result = AsyncHelper.RunSync(client.Groups.CreateGroupAsync(options, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);

            foreach (string member in members)
            {
                AsyncHelper.RunSync(client.Groups.AddUserToGroupAsync(result.Id, member, 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));
        }
Example #3
0
 /// <summary>
 ///     Initialise a new instance of the Okta JWT Security Token Handler
 /// </summary>
 /// <param name="tokenService">The Token Service.</param>
 /// <param name="tokenValidator">Token validator.</param>
 /// <param name="userSessionUpdateOktaTokenService">User update okta token service.</param>
 /// <param name="userSessionRetrievalByOktaIdService">User retrieval by okta id service.</param>
 /// <param name="userRetrievalById">User retrieval by id service.</param>
 /// <param name="userRetrievalByEmailService">User retrieval by email service.</param>
 /// <param name="userRetrievalByOktaId">User retrieval by okta id.</param>
 /// <param name="userUpdateService">Update user service.</param>
 /// <param name="userCreationService">User creation service.</param>
 /// <param name="oktaClient">Okta client.</param>
 /// <param name="oktaTokenExpiryTime">Okta token expiry time.</param>
 public OktaJwtSecurityTokenHandler(
     ITokenService tokenService,
     ISecurityTokenValidator tokenValidator,
     IAsyncQueryHandler <UserSessionUpdateOktaTokenQuery, MeUserSession> userSessionUpdateOktaTokenService,
     IAsyncQueryHandler <UserSessionRetrievalByOktaIdQuery, MeUserSession> userSessionRetrievalByOktaIdService,
     IAsyncQueryHandler <UserRetrievalByIdQuery, MeUser> userRetrievalById,
     IAsyncQueryHandler <UserRetrievalByOktaIdQuery, MeUser> userRetrievalByOktaId,
     IAsyncQueryHandler <UserRetrievalByEmailQuery, MeUser> userRetrievalByEmailService,
     IAsyncQueryHandler <UserUpdateQuery, MeUser> userUpdateService,
     IAsyncQueryHandler <CreateUserQuery, MeUser> userCreationService,
     IOktaClient oktaClient,
     int oktaTokenExpiryTime)
 {
     _tokenHandler = tokenValidator;
     _tokenService = tokenService;
     _userSessionUpdateOktaTokenService = userSessionUpdateOktaTokenService;
     _oktaTokenExpiryTime = oktaTokenExpiryTime;
     _userSessionRetrievalByOktaIdService = userSessionRetrievalByOktaIdService;
     _userRetrievalByEmailService         = userRetrievalByEmailService;
     _userCreationService   = userCreationService;
     _userRetrievalByOktaId = userRetrievalByOktaId;
     _userRetrievalById     = userRetrievalById;
     _userUpdateService     = userUpdateService;
     _oktaClient            = oktaClient;
 }
Example #4
0
        private CSEntryChangeResult PutCSEntryChangeDelete(CSEntryChange csentry, ExportContext context)
        {
            IOktaClient client = ((OktaConnectionContext)context.ConnectionContext).Client;

            AsyncHelper.RunSync(client.Groups.DeleteGroupAsync(csentry.DN, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);

            return(CSEntryChangeResult.Create(csentry.Identifier, null, MAExportError.Success));
        }
Example #5
0
        /// <summary>
        /// Create an Org2Org Application
        /// </summary>
        public static async Task <IOrg2OrgApplication> CreateOrg2OrgApplicationAsync(
            this IOktaClient spokeClient,
            CreateOrg2OrgApplicationOptions options,
            CancellationToken cancellationToken)
        {
            var requestUrl = spokeClient.Configuration.BuildUrl("/api/v1/apps");

            return(await spokeClient.PostAsync <Org2OrgApplication>(requestUrl.AbsoluteUri, options, cancellationToken));
        }
Example #6
0
 internal new void Initialize(
     IOktaClient client,
     ResourceFactory resourceFactory,
     IDictionary <string, object> data,
     ILogger logger)
 {
     resourceFactory = resourceFactory ?? new ResourceFactory(client, logger, new AbstractResourceTypeResolverFactory(ResourceTypeHelper.GetAllDefinedTypes(typeof(Resource))));
     base.Initialize(client, resourceFactory, data, logger);
 }
Example #7
0
        public RequireProfileCompletionFilter(IOktaClient oktaClient)
        {
            _oktaClient = oktaClient;

            _safeUrls = new[]
            {
                "/Account/Logout",
                "/Account/CompleteProfile"
            };
        }
Example #8
0
        /// <summary>
        /// Create an OIDC Application
        /// </summary>
        public static async Task <IOpenIdConnectApplication> UpdateOidcApplicationAsync(
            this IOktaClient client,
            string appId,
            UpdateOidcApplicationOptions options,
            CancellationToken cancellationToken)
        {
            var requestUrl = client.Configuration.BuildUrl($"/api/v1/apps/{appId}");

            return(await client.PutAsync <OpenIdConnectApplication>(requestUrl.AbsoluteUri, options, cancellationToken));
        }
Example #9
0
 public void Initialize(
     IOktaClient client,
     ResourceFactory resourceFactory,
     IDictionary <string, object> data,
     ILogger logger)
 {
     _client          = client;
     _resourceFactory = resourceFactory ?? new ResourceFactory(client, logger, new AbstractResourceTypeResolverFactory(ResourceTypeHelper.AllDefinedTypes));
     _data            = data ?? _resourceFactory.NewDictionary(null);
     _logger          = logger ?? NullLogger.Instance;
 }
Example #10
0
 internal void Initialize(
     IOktaClient client,
     ResourceFactory resourceFactory,
     IDictionary <string, object> data,
     ILogger logger)
 {
     _client          = client;
     _resourceFactory = resourceFactory ?? new ResourceFactory(client, logger);
     _data            = data ?? _resourceFactory.NewDictionary(null);
     _logger          = logger ?? NullLogger.Instance;
 }
Example #11
0
        private CSEntryChangeResult PutCSEntryChangeDelete(CSEntryChange csentry, ExportContext context)
        {
            IOktaClient client = ((OktaConnectionContext)context.ConnectionContext).Client;

            AsyncHelper.RunSync(client.Users.DeactivateUserAsync(csentry.DN, cancellationToken: context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);

            if (context.ConfigParameters[ConfigParameterNames.UserDeprovisioningAction].Value == "Delete")
            {
                AsyncHelper.RunSync(client.Users.DeactivateOrDeleteUserAsync(csentry.DN, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
            }

            return(CSEntryChangeResult.Create(csentry.Identifier, null, MAExportError.Success));
        }
        public Schema GetMmsSchema(SchemaContext context)
        {
            IOktaClient client = ((OktaConnectionContext)context.ConnectionContext).Client;

            Schema     mmsSchema = new Schema();
            SchemaType mmsType   = SchemaProvider.GetSchemaTypeUser(client);

            mmsSchema.Types.Add(mmsType);

            mmsType = SchemaProvider.GetSchemaTypeGroup(client);
            mmsSchema.Types.Add(mmsType);

            return(mmsSchema);
        }
        private static SchemaType GetSchemaTypeUser(IOktaClient client)
        {
            SchemaType      mmsType      = SchemaType.Create("user", true);
            SchemaAttribute mmsAttribute = SchemaAttribute.CreateAnchorAttribute("id", AttributeType.String, AttributeOperation.ImportOnly);

            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("status", AttributeType.String);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("created", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("activated", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("statusChanged", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("lastLogin", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("lastUpdated", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("passwordChanged", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("provider.type", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("provider.name", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateMultiValuedAttribute("enrolledFactors", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateMultiValuedAttribute("availableFactors", AttributeType.String, AttributeOperation.ImportOnly);
            mmsType.Attributes.Add(mmsAttribute);

            mmsAttribute = SchemaAttribute.CreateSingleValuedAttribute("suspended", AttributeType.Boolean, AttributeOperation.ImportExport);
            mmsType.Attributes.Add(mmsAttribute);

            foreach (SchemaAttribute a in SchemaProvider.GetSchemaJson(client))
            {
                mmsType.Attributes.Add(a);
            }

            return(mmsType);
        }
Example #14
0
        /// <summary>
        /// Method to get a printable form of Okta User Attributes
        /// </summary>
        /// <param name="user">Okta User object</param>
        /// <param name="attributes">Collection of attribute names</param>
        /// <param name="oktaClient">Okta Client</param>
        /// <param name="ofs">Output fields separator</param>
        /// <returns>String representing user attributes</returns>
        public static async Task <string> PrintAttributesAsync(this IUser user, IEnumerable <string> attributes,
                                                               IOktaClient oktaClient = null, string ofs = " ")
        {
            var attrList = attributes.ToList();

            var values = new[]
            {
                new[] { $"{user.Id}" },
                attrList
                .Where(attr => UserAttributes.NonProfileAttributes.Contains(attr))
                .Select(user.GetNonProfileAttribute),
                attrList
                .Where(attr =>
                       !UserAttributes.NonProfileAttributes.Contains(attr) &&
                       !UserAttributes.GroupAttributes.Contains(attr))
                .Select(attr =>
                {
                    if (user.Profile[attr] is IEnumerable <object> coll)
                    {
                        var str = string.Join(',', coll.Select(val => val.ToString()));
                        return($"({str})");
                    }

                    return(user.Profile[attr]?.ToString());
                })
            }
            .Where(lst => lst.Any())
            .SelectMany(x => x)
            .Select(attr => !string.IsNullOrEmpty(attr) && attr.Contains(ofs) ? $"\"{attr}\"" : attr);

            if (!attrList.Any(a => UserAttributes.GroupAttributes.Contains(a)))
            {
                return(string.Join(ofs, values));
            }

            if (oktaClient == null)
            {
                throw new Exception("Can't get group attributes without an instance of Okta Client");
            }

            //todo Name hardcoded as the only supported attribute for now
            values = values.Concat(new[] { await oktaClient.Users
                                           .ListUserGroups(user.Id)
                                           .Select(grp =>
                                                   $"({grp.Profile.Name})")
                                           .Aggregate(string.Concat) });

            return(string.Join(ofs, values));
        }
Example #15
0
        private CSEntryChangeResult PutCSEntryChangeUpdate(CSEntryChange csentry, ExportContext context)
        {
            IOktaClient client = ((OktaConnectionContext)context.ConnectionContext).Client;

            IGroup group = null;

            foreach (AttributeChange change in csentry.AttributeChanges)
            {
                if (change.Name == "name")
                {
                    if (group == null)
                    {
                        group = AsyncHelper.RunSync(client.Groups.GetGroupAsync(csentry.DN, null, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
                    }

                    group.Profile.Name = change.GetValueAdd <string>();
                }
                else if (change.Name == "description")
                {
                    if (group == null)
                    {
                        group = AsyncHelper.RunSync(client.Groups.GetGroupAsync(csentry.DN, null, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
                    }

                    group.Profile.Description = change.GetValueAdd <string>();
                }
                else if (change.Name == "member")
                {
                    foreach (string add in change.GetValueAdds <string>())
                    {
                        AsyncHelper.RunSync(client.Groups.AddUserToGroupAsync(csentry.DN, add, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
                    }

                    foreach (string delete in change.GetValueDeletes <string>())
                    {
                        AsyncHelper.RunSync(client.Groups.RemoveGroupUserAsync(csentry.DN, delete, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
                    }
                }
            }

            if (group != null)
            {
                AsyncHelper.RunSync(client.Groups.UpdateGroupAsync(group, csentry.DN, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
            }

            return(CSEntryChangeResult.Create(csentry.Identifier, null, MAExportError.Success));
        }
        private async Task CreateRandomUser(IOktaClient client, ConcurrentBag <IUser> createdUsers)
        {
            var randomGuid = Guid.NewGuid();

            var user = await client.Users.CreateUserAsync(new CreateUserWithoutCredentialsOptions
            {
                Profile = new UserProfile
                {
                    FirstName = $"Jack-{randomGuid}",
                    LastName  = "CollectionEnumeration",
                    Email     = $"collection-enumeration-dotnet-sdk-{randomGuid}@example.com",
                    Login     = $"collection-enumeration-dotnet-sdk-{randomGuid}@example.com",
                },
                Activate = false,
            });

            createdUsers.Add(user);
        }
Example #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UsersController"/> class.
 /// </summary>
 /// <param name="logger">The Logger.</param>
 /// <param name="mapper">The Mapper.</param>
 /// <param name="usersRetrievalByOktaIdService">User Retrieval By Okta Id Service.</param>
 /// <param name="authorizationService">Authorization Service.</param>
 /// <param name="permissionService">Permission Service.</param>
 /// <param name="userCreationService">User creation service.</param>
 /// <param name="userRetrievalByIdService">User retrieval service.</param>
 /// <param name="usersRetrievalService">Users retrieval service.</param>
 /// <param name="userUpdateService">The userToCreate update service</param>
 /// <param name="oktaClient">Okta client.</param>
 public UsersController(
     IAsyncQueryHandler <CreateMELoggerQuery, LogMessageActionDefault> logger,
     IMapper mapper,
     IAsyncQueryHandler <UserRetrievalByOktaIdQuery, MeUser> usersRetrievalByOktaIdService,
     IAuthorizationService authorizationService,
     IPermissionService permissionService,
     IAsyncQueryHandler <CreateUserQuery, MeUser> userCreationService,
     IAsyncQueryHandler <UserRetrievalByIdQuery, MeUser> userRetrievalByIdService,
     IAsyncQueryHandler <UsersRetrievalQuery, IEnumerable <MeUser> > usersRetrievalService,
     IAsyncQueryHandler <UserUpdateQuery, MeUser> userUpdateService,
     IOktaClient oktaClient)
     : base(logger, mapper, usersRetrievalByOktaIdService, authorizationService, permissionService)
 {
     _userCreationService      = userCreationService;
     _userRetrievalByIdService = userRetrievalByIdService;
     _usersRetrievalService    = usersRetrievalService;
     _userUpdateService        = userUpdateService;
     _oktaClient = oktaClient;
 }
        /// <summary>
        /// Ensure that the application in the destination okta tenant exists and exactly matches the provided one
        /// </summary>
        /// <param name="client"></param>
        /// <param name="targetState"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static async Task EnsureApplication(this IOktaClient client, Application targetState, CancellationToken cancellationToken)
        {
            //Attempt to get the existing application by looking it up based on label
            var currentState = await GetIfExists(() =>
                                                 client.GetAsync <Application>($"/api/v1/apps?q={Uri.EscapeDataString(targetState.Label)}",
                                                                               cancellationToken));

            if (currentState.CurrentState != EntityState <Application> .State.DoesNotExist)
            {
                //If it exists already, but doesn't match, then we need to override it
                await client.Applications.UpdateApplicationAsync(targetState, currentState.Entity.Id, cancellationToken);
            }
            else
            {
                await client.Applications.CreateApplicationAsync(targetState,
                                                                 activate : true,
                                                                 cancellationToken : cancellationToken);
            }
        }
        public static IEnumerable <SchemaAttribute> GetSchemaJson(IOktaClient client)
        {
            Resource result = AsyncHelper.RunSync(client.GetAsync <Resource>(
                                                      new HttpRequest
            {
                Uri = "/api/v1/meta/schemas/user/default",
            }));


            IDictionary <string, object> definitions = result["definitions"] as IDictionary <string, object>;

            foreach (SchemaAttribute schemaAttribute in SchemaProvider.GetAttributesFromDefinition(definitions, "base"))
            {
                yield return(schemaAttribute);
            }

            foreach (SchemaAttribute schemaAttribute in SchemaProvider.GetAttributesFromDefinition(definitions, "custom"))
            {
                yield return(schemaAttribute);
            }
        }
Example #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UsersController"/> class.
 /// </summary>
 /// <param name="logger">The Logger.</param>
 /// <param name="mapper">The Mapper.</param>
 /// <param name="usersRetrievalByOktaIdService">User Retrieval By Okta Id Service.</param>
 /// <param name="authorizationService">Authorization Service.</param>
 /// <param name="permissionService">Permission Service.</param>
 /// <param name="userCreationService">User creation service.</param>
 /// <param name="userRetrievalByIdService">User retrieval service.</param>
 /// <param name="usersRetrievalService">Users retrieval service.</param>
 /// <param name="userUpdateService">The userToCreate update service</param>
 /// <param name="locationsRetrievalService">Locations Retrieval Service.</param>
 /// <param name="oktaClient">Okta client.</param>
 public ProfileController(
     IAsyncQueryHandler <CreateMELoggerQuery, LogMessageActionDefault> logger,
     IMapper mapper,
     IAsyncQueryHandler <UserRetrievalByOktaIdQuery, MeUser> usersRetrievalByOktaIdService,
     IAuthorizationService authorizationService,
     IPermissionService permissionService,
     IAsyncQueryHandler <CreateUserQuery, MeUser> userCreationService,
     IAsyncQueryHandler <UserRetrievalByIdQuery, MeUser> userRetrievalByIdService,
     IAsyncQueryHandler <UsersRetrievalQuery, IEnumerable <MeUser> > usersRetrievalService,
     IAsyncQueryHandler <UserUpdateQuery, MeUser> userUpdateService,
     IAsyncQueryHandler <LocationsRetrievalByQuery, IEnumerable <Location> > locationsRetrievalService,
     IOktaClient oktaClient,
     IAsyncQueryHandler <LocationsParentsQuery, IDictionary <string, IEnumerable <Location> > > locationsParentsService)
     : base(logger, mapper, usersRetrievalByOktaIdService, authorizationService, permissionService)
 {
     _userCreationService       = userCreationService;
     _userRetrievalByIdService  = userRetrievalByIdService;
     _usersRetrievalService     = usersRetrievalService;
     _userUpdateService         = userUpdateService;
     _locationsRetrievalService = locationsRetrievalService;
     _oktaClient = oktaClient;
     _locationsParentsService = locationsParentsService;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceFactory"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="logger">The logging interface.</param>
 public ResourceFactory(IOktaClient client, ILogger logger)
 {
     _client = client;
     _logger = logger;
 }
 public AccountController(IOktaClient oktaClient = null)
 {
     _oktaClient = oktaClient;
 }
 public OktaTodoItemService(IOktaClient oktaClient)
 {
     _oktaClient = oktaClient;
 }
Example #24
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));
        }
Example #25
0
        private CSEntryChangeResult PutCSEntryChangeUpdate(CSEntryChange csentry, ExportContext context)
        {
            IOktaClient client = ((OktaConnectionContext)context.ConnectionContext).Client;

            IUser user    = null;
            bool  partial = true;

            if (csentry.AttributeChanges.Any(t =>
                                             t.ModificationType == AttributeModificationType.Delete ||
                                             t.Name == "suspended" ||
                                             t.DataType == AttributeType.Reference // this should only need to include MV attributes, but there's an issue where MIM sends an attribute update with a value delete for a single valued ref that it doesn't know about
                                             ))
            {
                logger.Trace($"Getting user {csentry.DN} for FULL update");
                user    = AsyncHelper.RunSync(client.Users.GetUserAsync(csentry.DN, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
                partial = false;
            }
            else
            {
                user         = new User();
                user.Profile = new UserProfile();
            }

            foreach (AttributeChange change in csentry.AttributeChanges)
            {
                if (change.Name == "suspended")
                {
                    bool suspend;

                    if (change.ModificationType == AttributeModificationType.Delete)
                    {
                        suspend = false;
                    }
                    else
                    {
                        suspend = change.GetValueAdd <bool>();
                    }

                    if (user.Status == UserStatus.Active && suspend)
                    {
                        logger.Info($"Suspending user {user.Id}");
                        AsyncHelper.RunSync(user.SuspendAsync(context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
                    }
                    else if (user.Status == UserStatus.Suspended && !suspend)
                    {
                        logger.Info($"Unsuspending user {user.Id}");
                        AsyncHelper.RunSync(user.UnsuspendAsync(context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
                    }
                }
                else
                {
                    if (change.IsMultiValued)
                    {
                        IList <object> existingItems = user.Profile[change.Name] as IList <object> ?? new List <object>();
                        IList <object> newList       = change.ApplyAttributeChanges((IList)existingItems);
                        user.Profile[change.Name] = newList;

                        logger.Info($"{change.ModificationType} {change.Name} -> {newList.Count} items");
                    }
                    else
                    {
                        user.Profile[change.Name] = change.GetValueAdd <object>();
                        logger.Info($"{change.ModificationType} {change.Name} -> {user.Profile[change.Name] ?? "<null>"}");
                    }
                }
            }

            if (partial)
            {
                AsyncHelper.RunSync(client.PostAsync <User>($"/api/v1/users/{csentry.DN}", user, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
            }
            else
            {
                AsyncHelper.RunSync(client.Users.UpdateUserAsync(user, csentry.DN, context.CancellationTokenSource.Token), context.CancellationTokenSource.Token);
            }

            return(CSEntryChangeResult.Create(csentry.Identifier, null, MAExportError.Success));
        }
Example #26
0
 public WorkItemService(IOktaClient oktaClient)
 {
     _oktaClient = oktaClient;
 }
 public OktaBlogService(IOktaClient oktaClient)
 {
     _oktaClient = oktaClient;
 }
Example #28
0
 /// <summary>
 /// Get a I that interacts with the Okta identity provider APIs
 /// </summary>
 /// <param name="client">A suitably authorised Okta client</param>
 /// <returns>An client for interacting with Okta identity providers</returns>
 public static IIdentityProvidersClient IdentityProviders(this IOktaClient client)
 {
     return(new IdentityProvidersClient(client));
 }
Example #29
0
 /// <summary>
 /// Get a ISettingsClient that interacts with the Okta settings APIs
 /// </summary>
 /// <param name="client">A suitably authorised Okta client</param>
 /// <returns>An client for interacting with Okta organisation settings</returns>
 public static IOrganisationSettingsClient OrganisationSettings(this IOktaClient client)
 {
     return(new OrganisationSettingsClient(client));
 }
Example #30
0
 /// <summary>
 /// Get a ISchemasClient that interacts with the Okta Schemas API
 /// </summary>
 /// <param name="client">A suitably authorised Okta client</param>
 /// <returns>An client for interacting with Okta schemas</returns>
 public static ISchemasClient Schemas(this IOktaClient client)
 {
     return(new SchemasClient(client));
 }