Is it possible to create guest users using Java SDK graph api?

Viewed 75

I am using this code to create users in Azure Active Directory from Java SDK. I have installed all required packages and libraries.

User user = new User();
user.accountEnabled = true;
user.displayName = "Kevin";
user.mailNickname = "kevin";
user.userPrincipalName = "kevin234@domain.onmicrosoft.com";
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.forceChangePasswordNextSignIn = true;
passwordProfile.password = "***********";
user.passwordProfile = passwordProfile;

graphClient.users()
    .buildRequest()
    .post(user);

I can create normal users but how to create guest users. I included user.userType='guest' in the above code

user.userPrincipalName = "kevin234@hotmail.com";
user.userType='guest'; // I added this that outputs Invalid Request error

graphClient.users()
   .buildRequest()
   .post(user);

Is there any easy way to do that using Graph API query? Can somebody suggest the changes I have to do in my code to achieve my scenario?

TIA

1 Answers

I tried to reproduce the same in my environment and got the below results:

To create guest users, you can make use of below query:

POST https://graph.microsoft.com/v1.0/invitations
Content-type: application/json

{
  "invitedUserEmailAddress": "kevin234@hotmail.com",
  "inviteRedirectUrl": "https://yourwebsite.com"
}

Response:

enter image description here

When I checked the Portal, guest user created successfully like below:

enter image description here

You can find the code snippet in Java beside your query response like below:

enter image description here

Code Sample in Java:

GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();

Invitation invitation = new Invitation();
invitation.invitedUserEmailAddress = "kevin234@hotmail.com";
invitation.inviteRedirectUrl = "https://yourwebsite.com";

graphClient.invitations()
.buildRequest()
.post(invitation);

Credits: Create invitation - Microsoft Docs

Related