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

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

Related

How do I specify the licensing query parameter for the Microsoft Teams API when using the Microsoft Graph SDK for Java?

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.

How to get an App Role's value with GRAPH API in Java

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();

How to optimize Bulk upload users Azure B2C JAVA?

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

Add AWS SQS Permission to all Principals through SDK

I'm trying to create an AWS SQS queue through the Java SDK, and then add all permissions for all users. I can create the queue fine, but I'm struggling to know what value I can pass in for the Principals. This is what my code looks like:
CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName).withAttributes(attributes);
CreateQueueResult createQueueResult = amazonSqs.createQueue(createQueueRequest);
String queueUrl = createQueueResult.getQueueUrl();
amazonSqs.addPermission(queueUrl, "*", ????, Arrays.asList("*"));
The ??? is what I'm not sure on. I've tried Arrays.asList("*") but it complains about it not being valid. In the web console, there is a checkbox for Everyone, and I'm just wanting to do the same thing in the SDK. Is there some value I can pass for this?
--- UPDATE ---
I've been able to accomplish this another way through a Policy:
String queueUrl = createQueueResult.getQueueUrl();
GetQueueAttributesResult getQueueAttributesResult = amazonSqs.getQueueAttributes(queueUrl, Arrays.asList(QUEUE_ARN_ATTRIBUTE_NAME));
String queueArn = getQueueAttributesResult.getAttributes().get(QUEUE_ARN_ATTRIBUTE_NAME);
if (needToSetPolicy)
{
Policy allAccessPolicy = new Policy("SQSAllAccess", Arrays.asList(
new Statement(Effect.Allow)
.withActions(() -> "SQS:*")
.withPrincipals(Principal.All)
.withId("SQSAllAccessStatement")
.withResources(new Resource(queueArn))
));
Map<String, String> policyMap = new HashMap<>(1);
policyMap.put(POLICY_ATTRIBUTE_NAME, allAccessPolicy.toJson());
amazonSqs.setQueueAttributes(queueUrl, policyMap);
}
It seems like there should be a better/easier way to do this. Are there any better/cleaner/easier ways of doing this?
In kotlin using the constants from the SDK
val policy: Policy = Policy("AllowAllSendMessage", listOf(Statement(Effect.Allow)
.withActions(SQSActions.SendMessage)
.withPrincipals(Principal.All)
.withId("AllowAllSendMessage")
.withResources(Resource(queueArn))))
_sqs.setQueueAttributes(SetQueueAttributesRequest()
.withQueueUrl(queueUrl)
.withAttributes(mapOf(QueueAttributeName.Policy.toString() to policy.toJson())))

Getting all ActiveDirectory groups using OpenSSO Client SDK

I hope someone here has experience with Sun OpenSSO (now ForgeRock OpenAM).
I'm trying to get all groups in ActiveDirectory using the OpenSSO Client SDK in Java / JBoss EAP 5.0.
I tried the following by combining various samples and code snippets I could find on the web, but this fails and eventually logs "Memberships for identities other than Users is not allowed." The basic approach was to use AMIdentityRepository -> getRealmIdentity() -> getMemberships(IdType.GROUP) :
SSOTokenManager manager = SSOTokenManager.getInstance();
String tokenString = URLDecoder.decode(tokenID, "ISO-8859-1");
SSOToken token = manager.createSSOToken(tokenString);
if (manager.isValidToken(token)) {
SSOToken adminToken = (SSOToken)AccessController.
doPrivileged(AdminTokenAction.getInstance());
AMIdentityRepository rep = new AMIdentityRepository(adminToken, "/");
AMIdentity identity = rep.getRealmIdentity();
Set groups = identity.getMemberships(IdType.GROUP);
}
Note I'm not trying to determine if a user is a member of a group or to retrieve a user's groups - I'm trying to get a list of ALL groups.
Any suggestions would be appreciated - thanks!
Instead of rep.getRealmIdentity() and then calling getMemberships(IdType.GROUP), use searchIdentities and getSearchResults like:
SSOToken token = (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance());
AMIdentityRepository ir = new AMIdentityRepository(token, "/");
IdSearchResults results = ir.searchIdentities(IdType.GROUP, "*", new IdSearchControl());
Set<AMIdentity> groups = results.getSearchResults();
for (AMIdentity group : groups) {
logger.debug("Group Name : " + group.getName());
}

Categories

Resources