Hi I need to migrate 20k users I have followed the Microsoft documentation for the SDK and saw some of the post on stack overflow but I still don't see how I can bulk upload my users to Azure AD B2C. The below method will take me 4 hours.
GraphServiceClient<Request> graphClient = GraphServiceClient.builder().authenticationProvider( tokenCredentialAuthProvider ).buildClient();
for (DBuser dbuser : users) {
com.microsoft.graph.models.User user = new com.microsoft.graph.models.User();
user.accountEnabled = true;
user.displayName = dbuser.getFirstName();
final LinkedList<ObjectIdentity> identitiesList = new LinkedList<ObjectIdentity>();
ObjectIdentity identities = new ObjectIdentity();
identities.signInType = "emailAddress";
identities.issuerAssignedId = dbuser.getEmail();
identities.issuer = "issuer";
identitiesList.add(identities);
user.identities = identitiesList;
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.password = dbuser.getPassword();
passwordProfile.forceChangePasswordNextSignIn = false;
user.passwordProfile = passwordProfile;
user.passwordPolicies = "DisablePasswordExpiration";
graphClient.users().buildRequest().post(user);
}
PowerShell script to create local accounts in bulk
Connect-azuread
$users = import-csv C:\temp\Admin.csv
$PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "P#$$w0rd"
foreach ($usr in $users)
{
New-AzureADUser -DisplayName $usr.name -PasswordProfile $PasswordProfile UserPrincipalName $usr.upn -AccountEnabled $true -MailNickName $usr.email
}
Below is how my C:\temp\test.csv file looks:
Reference : Use Graph Call for Social Accounts :
https://learn.microsoft.com/en-us/graph/api/user-post-users?view=graph-rest-1.0&tabs=http#example-2-create-a-user-with-social-and-local-account-identities
Creating bulk social identities via Graph API, you can combine multiple requests in one HTTP call using JSON batching as documented here: https://learn.microsoft.com/en-us/graph/json-batching
Note: You may need to modify it as per your requirement
Related
I have created a cluster, resource, service inside a stack using Java AWS SDK.
Now I need to fetch the Public IP of the task inside the cluster.
I have used ClientFormationCloud and am trying to fetch the IP using this client itself.
I have used the following code as of now:
String awsRegion = System.getenv("AWS_DEFAULT_REGION");
Region region = Region.of(awsRegion);
CloudFormationClient cfClient = CloudFormationClient.builder().region(region)
.credentialsProvider(EnvironmentVariableCredentialsProvider.create()).build();
CloudFormationWaiter waiter = cfClient.waiter();
Collection<Capability> capabilities = new ArrayList<Capability>();
capabilities.add(Capability.CAPABILITY_NAMED_IAM);
CreateStackRequest stackRequest = CreateStackRequest.builder().stackName(stackName).templateURL(location).capabilities(capabilities).roleARN(roleARN).onFailure(OnFailure.ROLLBACK).build();
CreateStackResponse cfResponse = cfClient.createStack(stackRequest);
DescribeStacksRequest stacksRequest = DescribeStacksRequest.builder().stackName(stackName).build();
DescribeStacksResponse response = cfClient.describeStacks();
WaiterResponse<DescribeStacksResponse> waiterResponse = waiter.waitUntilStackCreateComplete(stacksRequest);
waiterResponse.matched().response().ifPresent(System.out::println);
'''
EDITED
Tried the following for ECS according to the first comment
'''
AmazonECS ecsClient = AmazonECSClientBuilder.standard().withRegion(System.getenv("AWS_DEFAULT_REGION")).withCredentials(new com.amazonaws.auth.EnvironmentVariableCredentialsProvider()).build();
ListTasksRequest request = new ListTasksRequest().withCluster("ClusterName");
ListTasksResult tasks = ecsClient.listTasks(request);
List<String> taskArns = tasks.getTaskArns();
for (String taskArn : taskArns) {
System.out.println(taskArn);
DescribeTasksRequest dtr = new DescribeTasksRequest().withTasks(taskArn);
DescribeTasksResult response = ecsClient.describeTasks(dtr);
}
'''
The taskArn is getting printed: arn:aws:ecs:us-east-1:892372858130:task/ClusterName/2c72e43671ef4cc09f7816469696ee3e
But the last line of the code is giving the following error:
com.amazonaws.services.ecs.model.InvalidParameterException: Invalid identifier: Identifier is for cluster NaraCluster. Your cluster is default (Service: AmazonECS; Status Code: 400; Error Code: InvalidParameterException; Request ID: 45f8abfc-66d4-4808-8810-b6e314bb1b15; Proxy: null)
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
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:
When I checked the Portal, guest user created successfully like below:
You can find the code snippet in Java beside your query response like below:
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
According to the Licensing and payment requirements for the Microsoft Teams API documentation, I need to include a model query parameter to specify the
licensing and payment model for the Microsoft Teams API. How do I do this when using the Microsoft Graph SDK for Java?
I currently access the Graph API using the com.microsoft.graph.requests.GraphServiceClient class:
public static GraphServiceClient<Request> getGraphClient(#NonNull final AadAuthenticationProperties properties,
#NonNull final String tenantId) {
var credential = new ClientSecretCredentialBuilder().clientId(properties.getCredential().getClientId())
.clientSecret(properties.getCredential().getClientSecret())
.tenantId(tenantId)
.build();
var authProvider = new TokenCredentialAuthProvider(
properties.getAuthorizationClients().get("graph").getScopes(), credential);
final var logger = new DefaultLogger();
logger.setLoggingLevel(LoggerLevel.DEBUG);
return GraphServiceClient.builder().authenticationProvider(authProvider).logger(logger).buildClient();
}
Is there someway that I should alter this client? Would this only be necessary for subscribing to change notifications? While for querying for all object details? While querying for certain particular object details?
Code Snippet that might help, the following is for getAllMessages model A.
You can modify it as per your needs but the underlying logic remains the same.
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var queryOptions = new List<QueryOption>()
{
new QueryOption("model", "A")
};
var getAllMessages = await graphClient.Users["Alexw#cqons.onMicrosoft.com"].Chats
.GetAllMessages()
.Request( queryOptions )
.GetAsync();
For all future readers, you can query this in Graph Explorer and go to the code snippet section to get the corresponding code snippet.
I am using GRAPH API via an application to connect to an AZURE AD. I am able to pull users/groups/roles. I can even pull app roles. However I need to be able to access the app roles value within my code and cannot figure out how to do so.
AppRoleAssignmentCollectionPage appRoleAssignments = graphClient.users(userId).appRoleAssignments()
.buildRequest()
.get();
List<AppRoleAssignment> memberRolesCurrentPage = appRoleAssignments.getCurrentPage();
if (memberRolesCurrentPage.isEmpty()) {
LOG.info("No app roles found for user");
} else {
ArrayList<String> roles = new ArrayList<String>();
for(AppRoleAssignment role : memberRolesCurrentPage) {
roles.add(role.principalDisplayName);
LOG.info( "ROLE: " + role.resourceDisplayName );
}
This is one way I am pulling data, but doing role."value" doesn't work and I can't figure out a way to get that data. Any suggestions?
Make sure you are already using below code at the starting of the code.
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
Here is an example of the request to retrieve the app roles that have been assigned to a user.
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
AppRoleAssignmentCollectionPage appRoleAssignments = graphClient.users("cdb555e3-b33e-4fd5-a427-17fadacbdfa7").appRoleAssignments()
.buildRequest()
.get();
I'm using the below code to get all the available volumes under EC2. But I can't find any Ec2 api to get already attached volumes with an instance. Please let me know how to get all attached volumes using instanceId.
EC2Api ec2Api = computeServiceContext.unwrapApi(EC2Api.class);
List<String> volumeLists = new ArrayList<String>();
if (null != volumeId) {
volumeLists.add(volumeId);
}
String[] volumeIds = volumeLists.toArray(new String[0]);
LOG.info("the volume IDs got from user is ::"+ Arrays.toString(volumeIds));
Set<Volume> ec2Volumes = ec2Api.getElasticBlockStoreApi().get()
.describeVolumesInRegion(region, volumeIds);
Set<Volume> availableVolumes = Sets.newHashSet();
for (Volume volume : ec2Volumes) {
if (volume.getSnapshotId() == null
&& volume.getStatus() == Volume.Status.AVAILABLE) {
LOG.debug("available volume with no snapshots ::" + volume.getId());
availableVolumes.add(volume);
}
}
The AWS Java SDK now provides a method to get all the block device mappings for an instance. You can use that to get a list of all the attached volumes:
// First get the EC2 instance from the id
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
DescribeInstancesResult describeInstancesResult = ec2.describeInstances(describeInstancesRequest);
Instance instance = describeInstancesResult.getReservations().get(0).getInstances().get(0);
// Then get the mappings
List<InstanceBlockDeviceMapping> mappingList = instance.getBlockDeviceMappings();
for(InstanceBlockDeviceMapping mapping: mappingList) {
System.out.println(mapping.getEbs().getVolumeId());
}
You can filter the output of the EC2 DescribeVolumes API call. There are various attachment.* filters available, the one you want is filtering by attached instance ID. Try the following code:
Multimap<String, String> filter = ArrayListMultimap.create();
filter.put("attachment.instance-id", instanceId);
filter.put("attachment.status", "attached");
Set<Volume> volumes = ec2Api.getElasticBlockStoreApi().get()
.describeVolumesInRegionWithFilter(region, volumeIds, filter);
The filter is a Multimap with the keys and values you want to filter on. You can actually specify the same filter multiple times, for example to get all volumes attached to a number of different instances.
You can use volumeAttachmentApi.listAttachmentsOnServer() to do this.
NovaApi novaApi = context.unwrapApi(NovaApi.class);VolumeApi volumeApi = novaApi.getVolumeExtensionForZone(region).get();
VolumeAttachmentApi volumeAttachmentApi = novaApi.getVolumeAttachmentExtensionForZone(region).get();
volumeAttachmentApi.listAttachmentsOnServer(serverId)