Adding User to Organization Unit and Group using Google Directory API
I am successful to create new user account using Google Directory API in .Net platform, but now I need to add that created user to Organization Unit and Group. I see the API details in this link to add the user to Organization Unit but any example showing insertion to Organization Unit would be greatly appreciated.
Updated with working code: Below is the code to create new user account using Directory API:
String serviceAccountEmail = "[email protected]";
X509Certificate2 certificate = new X509Certificate2(@"C:\key.p12", "secret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[]
{
DirectoryService.Scope.AdminDirectoryUser
},
User = "[email protected]",
}.FromCertificate(certificate));
var ser = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Google Account",
});
try
{
var user = new Google.Apis.Admin.Directory.directory_v1.Data.User()
{
Name = new Google.Apis.Admin.Directory.directory_v1.Data.UserName()
{
GivenName = FirstName.Text,
FamilyName = LastName.Text
},
Password = password
};
User newUser = new User();
UserName newUserName = new UserName();
newUser.PrimaryEmail = Email.Text;
newUserName.GivenName = FirstName_txt.Text;
newUserName.FamilyName = LastName_txt.Text;
newUser.Name = newUserName;
newUser.Password = password;
//Adding User to OU:
newUser.OrgUnitPath = "/Employee";
User results = ser.Users.Insert(newUser).Execute();
//Adding User to Group:
Member newMember = new Member();
newMember.Email = Email.Text;
newMember.Role = "MEMBER";
newMember.Kind = "admin#directory#member";
api.Members.Insert(newMember, "[email protected]").Execute();
Any idea how to insert the created user in Organization Unit and Group using Directory API?
Solution 1:
To insert the new user into a Organization Unit just set the OU path when you create the user.
User newUser = new User();
UserName newUserName = new UserName();
newUser.PrimaryEmail = Email.Text;
newUserName.GivenName = FirstName_txt.Text;
newUserName.FamilyName = LastName_txt.Text;
newUser.Name = newUserName;
newUser.Password = password;
**newUser.OrgUnitPath ="\My\Organization\Unit\path\";**
User results = ser.Users.Insert(newUser).Execute();
Now your user has been added to the OU path.
To add a member into a group see the following code.
Member newMember = new Member();
newMember.Email = userKey;//email of the user that you want to add
newMember.Role = "MEMBER";
newMember.Type = "USER";
newMember.Kind = "admin#directory#member";
ser.Members.Insert(newMember, "MyDestinationGroup@mydomain").Execute();
that's it.
Note: you must review the scopes for the correct permissions.
Hope this help you.