0

I am trying to create a Java Console Application to bulk upload users from local SQL database to Azure b2c active directory. I have a JSON file which I created

{
  "users": [
    {
      "displayName": "Amanda Polly",
      "givenName": "Amanda",
      "surname": "Polly",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "emailAddress",
          "issuerAssignedId": "amandapolly@gmail.com"
        }
      ],
      "extension_timezone": "PST",
      "extension_locale": "en-US",
      "extension_tenant": "EG1234"
    },
    {
      "displayName": "Lowa Doe",
      "givenName": "Lowa",
      "surname": "Doe",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "userName",
          "issuerAssignedId": "lowadow123"
        }
      ],
      "extension_timezone": "PST",
      "extension_locale": "en-US",
      "extension_tenant": "EG1234"
    }
   ]
}

These are the users which I want to create on B2C, I need help in starting this, I have to use microsoft graph API, can anyone guide me through, I read about tokens and clientID but was not able to understand it.

enter image description here

It is stuck in this state for a long time. deserializing to JSON

SharadxDutta
  • 1,058
  • 8
  • 21

1 Answers1

1

To call Microsoft Graph, your app must acquire an access token from the Microsoft identity platform. The access token contains information about your app and the permissions it has for the resources and APIs available through Microsoft Graph. To get an access token, your app must be registered with the Microsoft identity platform and be authorized by either a user or an administrator for access to the Microsoft Graph resources it needs.

There are two kinds of common auth flow: client_credentials flow and authorization_code flow. The former is app-only, and the latter is app+user.

Here I take "client_credentials flow" as the example.

Firstly you need to Register your app. More detailed steps here. Remember to add and grant consent to User.ReadWrite.All application permission in your Azure AD app.

enter image description here

After you add the permission, don't forget to click on "Grant admin consent for {your tenant}" (see it below).

enter image description here

Create a client secret is necessary. (record it once it is created because you won't see it later).

enter image description here

Also remember to record the application id (client id) for late use.

enter image description here

Now you can Install the Microsoft Graph Java SDK to your project and implement Client credentials provider like this:

ClientCredentialProvider authProvider = new ClientCredentialProvider(
                                                    clientId,
                                                    scopes,
                                                    clientSecret,
                                                    tenant,
                                                    endpoint);

You should have clientId and clientSecret from the previous steps. scopes should be "https://graph.microsoft.com/.default". tenant should be the tenant id of your B2C tenant. endpoint is the NATIONAL_CLOUD of Microsoft. See the sample here.

Then you could use the following code to create user. See reference here.

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

User user = new User();
user.displayName = "John Smith";
LinkedList<ObjectIdentity> identitiesList = new LinkedList<ObjectIdentity>();
ObjectIdentity identities = new ObjectIdentity();
identities.signInType = "userName";
identities.issuer = "contoso.onmicrosoft.com";
identities.issuerAssignedId = "johnsmith";
identitiesList.add(identities);
ObjectIdentity identities1 = new ObjectIdentity();
identities1.signInType = "emailAddress";
identities1.issuer = "contoso.onmicrosoft.com";
identities1.issuerAssignedId = "jsmith@yahoo.com";
identitiesList.add(identities1);
ObjectIdentity identities2 = new ObjectIdentity();
identities2.signInType = "federated";
identities2.issuer = "facebook.com";
identities2.issuerAssignedId = "5eecb0cd";
identitiesList.add(identities2);
user.identities = identitiesList;
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.password = "password-value";
passwordProfile.forceChangePasswordNextSignIn = false;
user.passwordProfile = passwordProfile;
user.passwordPolicies = "DisablePasswordExpiration";

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

Modify the code based on your needs.

Besides, if you want to add extension attributes, you need to refer to Create extensionProperty. You should create extensionProperty first and then create the users with extension attributes. See my another answer for the logic. (just need to look into the content before "Then create a claimsMappingPolicy:")

Allen Wu
  • 15,529
  • 1
  • 9
  • 20
  • I am working on your solution, will let you know if it works, also I am hoping that it works, give me 2-3 hours to implement this. – SharadxDutta Aug 21 '20 at 08:32
  • ClientCredentialProvider cannot be resolved to a type, why is this coming? – SharadxDutta Aug 21 '20 at 10:22
  • 1
    @sh4r4d Looks like you didn't install the required [package](https://learn.microsoft.com/en-us/graph/sdks/sdk-installation#install-the-microsoft-graph-java-sdk-via-maven). – Allen Wu Aug 21 '20 at 23:53
  • 1
    @sh4r4d Besides, do you have to do it with your own java console app? If your goal is just to create users but don't want to deal with access tokens, you can use [Microsoft Graph Explorer](https://developer.microsoft.com/en-us/graph/graph-explorer). Log in with your administrator account and use http directly. Please see the http [example](https://learn.microsoft.com/zh-tw/graph/api/user-post-users?view=graph-rest-1.0&tabs=http#request-1). – Allen Wu Aug 21 '20 at 23:57
  • Hello Allen, after following what you said! I was able to do it, thank you so much, the problem was with the maven dependencies missing, I corrected it. – SharadxDutta Aug 22 '20 at 06:34
  • As of now User user = graphClient.me().buildRequest().get(); --> for this i am getting now response, below is the error – SharadxDutta Aug 22 '20 at 06:35
  • SEVERE: CoreHttpProvider[send] - 204Error message: Resource '70c68ef2-5d4d-4bce-9def-1af97bcc758d' does not exist or one of its queried reference-property objects are not present – SharadxDutta Aug 22 '20 at 06:35
  • 1
    @sh4r4d You are using confidential client flow (app-only), there is not a signed-in user. In this case you cannot use `graphClient.me()`. You should use `User user = graphClient.users("allenwu@tenant.onmicrosoft.com").buildRequest().get();` If you want to use `graphClient.me()`, you should implement [authorization_code flow](https://learn.microsoft.com/en-us/graph/auth-v2-user?view=graph-rest-1.0) and [Authorization code provider](https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=Java#authorization-code-provider). – Allen Wu Aug 24 '20 at 05:24
  • how can I get the list of all users under tenant -> tenant.onmicrosoft.com, – SharadxDutta Aug 24 '20 at 05:40
  • @sh4r4d Just use `IUserCollectionPage users = graphClient.users().buildRequest().get();` – Allen Wu Aug 24 '20 at 05:47
  • I tried this, Aug 23, 2020 10:52:59 PM com.microsoft.graph.logger.DefaultLogger logDebug INFO: Deserializing type UserCollectionResponse --> stuck in this state for past 15 mins – SharadxDutta Aug 24 '20 at 05:53
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/220340/discussion-between-sh4r4d-and-allen-wu). – SharadxDutta Aug 24 '20 at 07:10
  • 1
    @sh4r4d I just make it. Use `System.out.println(user.getRawObject().getAsJsonObject().toString());` – Allen Wu Aug 24 '20 at 08:28
  • LinkedList identitiesList = new LinkedList(); --> when I tried this "ObjectIdentity" is throwing error --> cannot be resolved to a type, is there a dependency that I need to add in maven? also I deleted the duplicate post. – SharadxDutta Aug 24 '20 at 09:26
  • @sh4r4d `import com.microsoft.graph.models.extensions.ObjectIdentity;` and `import java.util.LinkedList;` – Allen Wu Aug 24 '20 at 09:30
  • import com.microsoft.graph.models.extensions.ObjectIdentity; --> this is giving me error, The import com.microsoft.graph.models.extensions.ObjectIdentity cannot be resolved – SharadxDutta Aug 25 '20 at 06:41
  • @sh4r4d Have sent you the pom.xml configuration here: https://chat.stackoverflow.com/rooms/220340/discussion-between-sh4r4d-and-allen-wu – Allen Wu Aug 25 '20 at 06:47