How to create users using Microsoft Graph API (from Graph explorer and Java application) - azure

I am new to Microsoft Graph API. I have read many articles on the web to understand the usage of Microosft Garph API for managing users in Azure AD. I am creating a Springboot based REST API service, which needs to create users in Azure AD.
I have registered my application in Azure Active Directory. I have also 'Directory.ReadWrite.All" permission for Microsoft Graph API. I wanted to first try to create the user from Microsoft Garph explorer. In the Graph Explorer, I have to give authorization token in the Request header. In order to create authorization token, I have followed the instruction given in the link https://learn.microsoft.com/en-us/graph/auth-v2-user. I have created the following URL based on the instruction, for obtaining Access token.
https://login.microsoftonline.com/{mytenantID}/oauth2/v2.0/authorize?client_id=validclientID&response_type=code&redirect_uri=https://localhost:4200&response_mode=query&scope=Directory.ReadWrite.All&state=12345
When the above URL is accessed from the web browser, I get a message which says "Need Admin Approval". I am not the admin of the Azure AD and I do not have access to the admin of my client, so I am really stuck. Can anybody help me understand whether I will have to get admin consent each time I need to access "create user" functionality of Azure AD through MS Graph API? . I would also also need the create user functionaltiy in the Springboot API. In this case, how would Admin Consent work?. Is there anyway that the create user functionality can work without Admin consent.
I have read the following two questions in SO before posting this question
How can I find the Admin Consent URL for an Azure AD App that requires Microsoft Graph "Read directory data" permission?
Create user using Microsoft Graph

if you just want to create a user in your tenant , you can follow the steps below :
Create a new Azure AD app in your tenant, ask your tenant admin to grant "Directory.ReadWrite.All" permission to this app :
Create a app secret for your Azure AD app :
Use this secret and this Azure AD app ID to get access_token to call Microsoft Graph API :
Request URL :
POST https://login.microsoftonline.com/<-your tenant name->/oauth2/v2.0/token
Request Header :
Content-Type: application/x-www-form-urlencoded
Request Body:
grant_type:client_credentials
client_id:your client Id
client_secret: Your application secret
scope=https://graph.microsoft.com/.default
You will get an access_token from this API calling.
See the screen shot below:
3. Using the access_token we just created to call Microsoft Graph API to create a user :
As you can see , a user has been created :
If you have any further concerns , pls feel free to let me know : )

Related

Integration with microsoft teams via API Postman

I try to integrate with microsoft teams i follow this documentation:
https://learn.microsoft.com/en-us/graph/use-postman
One of require request to get access token fill "Username" and "Password"
I don't have any idea how to get this 2 value and from where!
Where i keep him blanc i receive :
The request body must contain the following parameter: 'username'.\r\nTrace ID: ......
Any idea?
POSTMAN collection needs username/password. To access any protected resource like Microsoft Graph API then follow the steps:
Register an Azure AD application based on your AAD workflows. Make sure it has necessary Graph permissions
Make sure you have M365 tenant/account, has username/password
Configure POSTMAN as per above AAD workflow and update the values
from two above steps (Azure AD app details, tenant info, username,
password)
Start using the POSTMAN collection, get the token from AAD, make call to Graph API/Teams.

Credentials prompt for access to Azure management APIs

I've been using the Azure fluent management APIs (https://github.com/Azure/azure-libraries-for-net) with some success in .NET Core.
However, I want to prompt the user to enter some credentials for a Microsoft account. Those credentials would have access to one or more Azure tenants / subscriptions, so I'd like to be able to use the result to browse and manage resources there.
This is something very close to what I would believe Azure Data Studio does: you can enter some Azure creds, and your resources will appear in the app.
I'm trying to understand the best approach for this. There seem to be a billion sites out there when you talk about Azure AD app registrations, but I haven't found a fruitful specific search query yet. I know I can register an app, get a client ID and client secret. I know I can set it to be usable by organisational accounts in the current tenant, or all tenants.
I can add the "Azure Service Management (delegated permissions : user_impersonation)" permission to my API permissions section for the app, but what's next?
If I use Microsoft.Identity.Client (as in https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-netcore-daemon), I run into some questions:
AcquireTokenForClientAsync doesn't prompt the user - I guess because it's getting a token for the app to act with its own permissions?
AcquireTokenOnBehalfOfAsync wants a JWT.. great! I'll pass the one I got from AcquireTokenForClientAsync! Nope, AADSTS70002: Error validating credentials. AADSTS500137: The token issuer doesn't match the api version: A version 1 token cannot be used with the v2 endpoint.
I don't know what scope I want. https://management.azure.com/user_impersonation is apparently invalid.. https://management.azure.com/.default works, but is that right? It's a guess, combo of the former and a .default suffix I found for Graph API scopes online. Any docs on this?
I ultimately get a JWT and tenant ID back. I can't find a way to use a JWT with the Fluent management APIs.. and my account (for instance) is associated with 3 tenants or 5 different tenants / directories - so how do I choose?
That's just what I've tried, the appropriate route might be a different one. In summary: I want a .NET Core Console app to request user credentials, and then get access to the Azure resources they have access to, in order to perform some resource management.
AcquireTokenForClientAsync doesn't prompt the user - I guess because it's getting a token for the app to act with its own permissions?
You are using the OAuth 2.0 client credentials grant to access web-hosted resources by using the identity of an application. This type of grant commonly is used for server-to-server interactions that must run in the background, without immediate interaction with a user .
AADSTS70002: Error validating credentials. AADSTS500137: The token issuer doesn't match the api version: A version 1 token cannot be used with the v2 endpoint.
Azure AD provide two service : Azure AD V1.0 and Azure AD V2.0 . Please refer to Comparing the Azure AD v2.0 endpoint with the v1.0 endpoint . You can't use v1 token to acquire v2's token in a on-behalf-of flow .
AcquireTokenOnBehalfOfAsync wants a JWT.. great! I'll pass the one I got from AcquireTokenForClientAsync
AS pointed above , That function is used to acquire an access token for this application (usually a Web API) from the authority configured in the application, in order to access another downstream protected Web API on behalf of a user using the OAuth 2.0 On-Behalf-Of flow. So you can't use app token which acquire using Client Credential flow .
https://management.azure.com/.default works, but is that right? It's a guess, combo of the former and a .default suffix I found for Graph API scopes online. Any docs on this?
You are using the Azure Active Directory v2.0 and the OAuth 2.0 client credentials flow , when sending a POST request to the /token v2.0 endpoint ,the scope should be :
The value passed for the scope parameter in this request should be the resource identifier (Application ID URI) of the resource you want, affixed with the .default suffix. For the Microsoft Graph example, the value is https://graph.microsoft.com/.default. This value informs the v2.0 endpoint that of all the direct application permissions you have configured for your app, it should issue a token for the ones associated with the resource you want to use.
Please check the Get a tokensection in above document .
I ultimately get a JWT and tenant ID back. I can't find a way to use a JWT with the Fluent management APIs..
AFAIK , currently Azure AD V2.0 apps can use:
Its own API
Microsoft Outlook APIs
Microsoft Graph API
Azure AD V2.0 currently doesn't support Azure management APIs .
So you problem is you need to allows work and school accounts from Azure AD and personal Microsoft accounts (MSA) which works with Azure AD V2.0 , but you can't use Azure management APIs . You can use Azure management APIs in Azure AD V1.0 but it allows only work and school accounts to sign in to your application , unless you invite Microsoft accounts as guest user in Azure AD V1.0 ,but you need to configure to point to the tenant-specific endpoint :https://login.microsoftonline.com/{TenantId_or_Name}). during authentication if you want to login with MSA in v1.0 apps.
Update:
You can use Code flow and azure ad v1.0 endpoint , user will be redirect to AAD's login page and enter their credential. Here is code sample for .net Core .
With Azure AD V1.0 endpoint , requests are sent to an endpoint that multiplexes across all Azure AD tenants: https://login.microsoftonline.com/common . When Azure AD receives a request on the /common endpoint, it signs the user in and, as a consequence, discovers which tenant the user is from. See document here . But in this scenerio ,you can only use work and school accounts(AAD) account to login .
The code sample in your link is using Azure Service Principal for Authentication , no interactive user login . You can use OpenID Connect Owin Middleware for authentication in .net Core applications as shown here .

Azure AD - get user's profile photo, OAUTH access failure

I'm trying to access the signed in user's Profile Photo in the context of an email app which uses EWS to connect to Office 365.
The app is registered on portal.azure.com with the following required permissions:
Office 365 Exchange Online -> Access mailboxes as the signed-in user via Exchange Web Services
Windows Azure Active Directory -> Sign in and read user profile
The EWS part works just fine, I'm able to sign the user in, get the access and refresh tokens, and perform EWS operations using "Authorization: Bearer access_token".
The part I'm having trouble with is getting the user's profile photo.
This is the docs I'm going by:
https://msdn.microsoft.com/en-us/office/office365/api/photo-rest-operations
The API endpoint I'm trying to use is:
GET https://outlook.office.com/api/v2.0/me/photo
... with "Authorization: Bearer access_token" header.
The above API returns this response:
HTTP 403
{"error":{"code":"ErrorAccessDenied","message":"Access is denied.
Check credentials and try again."}}
What could be wrong?
According to the above docs, getting user's photo should be possible using the user.read scope.
The "Sign in and read user profile" permission I mentioned above has a tooltip saying "User.Read", so I believe that's the right scope
I've tried decoding my access token at jwt.io, it has: "scp": "full_access_as_user" - where is my User.Read scope, or does "full access" include "user.read"?
Any ideas?
This is because that you tried use v2 endpoint Rest API but you didn't register the Application with v2 endpoint.
User Photo API is only available on Azure AD v2 authentication endpoint, Not Azure AD and Oauth:
You need to go to Microsoft Application Registration Portal to register your Application. For more details , you can refer to this document.
Just for the record:
Since we were not able to use OAUTH2 APIs for this -
since and our app uses EWS (Exchange Web Services) already...
We just ended up using the GetUserPhoto command with the user's (account's) own email address.
Works fine.

How do I register an app in client's active directory using my multi tenant app in microsoft azure?

I have registered a multi-tenant app in my Azure subscription. using this App, I want to create an OAuth flow for my client to be able to give me permissions to create an app in his active directory.
We are using OpenID connect flow to access the Azure AD graph API.
In spite of making our app multi-tenanted via the console, we are getting the following error when the client (xyz#outlook.com) tries to sign in:
User account 'xyz#outlook.com' from identity provider 'live.com' does not exist in tenant 'Default Directory' and cannot access the application 'bf5ca806-xxxx-xxxx-xxx-xxxx' in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account
I used the following endpoint to get an access token:
https://login.microsoftonline.com/common/oauth2/authorize?
client_id=xxxxxxxx-xxxx-xxxxx-xxxx-xxxxx
&response_mode=form_post
&response_type=code+id_token
&redirect_uri=http://localhost:8080
&prompt=admin_consent
&nonce=1234
&resource=https://graph.windows.net
Please help me to resolve this error
Unfortunately, you cannot use a guest user to login Azure AD Graph Explorer for now.
I came across the same issue as yours long time ago and I understand it's very important for customers. So, you can post your idea in this User Voice Page and the Azure Team will see it. I will also upvote for it.
But there are other solutions if you don't mind:
Solution 1: Try to use an internal account of that directory which upn ends with .onmicrosoft.com
Solution 2: Try to use other tools to get access token with a guest user(this account also need to be an admin of that directory), such as postman. Then you can use Postman to call Azure AD Graph API. You can refer to this blog to use Azure AD Graph API with Postman.
Hope this helps!

Azure AD authentication to call Office 365 and Graph API REST

I've created a sample MVC app using VS 2015 and used Azure AD Auth wizard. When I launch this web application, it asked me to register app with Azure AD (first time only) and then userid/password. I have entered Office 365/Azure AD account and successfully logged in. Everything is working perfectly fine and at the top right, I can see Hello "myname".
Now I tried to make REST call to Office 365 using RestSharp. It is giving me 403 error (access denied).
When I tried to use graph api url https://graph.windows.net/testname.com/groups?api-version=1.6, I am getting error unauthorized access.
Here is my test code with graph API call:
string url = "https://graph.windows.net/testname.com/groups?api-version=1.6";
var client = new RestClient(url);
client.ClearHandlers();
var jsonDeserializer = new JsonDeserializer();
client.AddHandler("application/json", jsonDeserializer);
var request = new RestRequest(Method.GET);
var queryResult = client.Execute(request);
I am using same code with O365 REST url for Office 365 call.
Why I am getting access denied in both cases if my app is already authenticated against Azure AD which is the base authentication. Also Request.IsAuthenticated is always true.
Isn't a single identity provider (AAD) used for Azure, Office 365 and related resources?
It's possible your app isn't configured to call the /groups endpoint of graph. While the end user is authenticated and you have gotten tokens for the Azure AD Graph (graph.windows.net), this access token needs to have a certain set of permissions to call the endpoints.
To configure these graph permissions, you can go to the Azure Portal, select Azure Active Directory, then App Registrations, and finally Required Permissions. The resource your calling is Windows Azure Active Directory and then you can look through the list of scopes for what you want to call.
Another great resource I'll recommend is the Azure AD Graph Explorer. This can help understand the type of data the graph can provide.
Edit: Checkout comments for answer. OP had used the OpenID Connect middleware (OWIN) and needed help getting an access token for a resource. In order to do this, you must use a combination of OWIN + ADAL. OWIN gets an auth code, and ADAL can exchange this auth code for an access token.

Resources