Azure Graph API: authorize application on multiple tenants - azure

I am trying to create an application to browse my contacts directory on Exchange.
I have set up everything and I am able request the authorization from my app.
I can present the modal view, enter the login information, retrieve the token, but when I try to authorize the app with the same account I have created it I get this message:
The client <my app id> and resource <my app URI> identify the same application.
If I try to authorize another account, I receive this message instead:
User account <an email> from external identity provider <a url> is not
supported for application <my app id>
If I try to login on the Graph Explorer Console or on the Office 365 OAuth Sandbox, they work fine with the second address, but not with the first one.
I am really confuse. I feel like I have mess up some configuration option, but I don't really understand which one.

Regarding #1, please do not pass App ID of your application for resource querystring parameter when authenticating against your tenant URL. I ran into the exact same problem.
Then I ran WebApp-MultiTenant-OpenIdConnect-DotNet from Github and noted down the sign-in URL it created and I used the following:
var signInUrl = String.Format(
"https://login.windows.net/{0}/oauth2/authorize?response_mode=form_post&response_type=code+id_token&scope=openid+profile&client_id={1}&resource={2}&redirect_uri={3}&state={4}&nonce={5}",
Uri.EscapeDataString(tenantId),
Uri.EscapeDataString(clientId),
Uri.EscapeDataString("https://graph.windows.net"),
Uri.EscapeDataString(redirectUri),
Uri.EscapeDataString(state),
string.Format("{0}{1}", DateTime.UtcNow.Ticks, Guid.NewGuid().Stringify())
);
Basically I used https://graph.windows.net instead of App ID and magically things started to work :).
Another thing you could try (and I have not tried it) is authenticating against common endpoint https://login.windows.net/common/oauth2/authorize and provide your App ID for the resource querystring.

Related

Postman with OAuth2.0 to a registered app in Azure Active Directory fails with Invalid Resource

I am following the tutorial here: https://learn.microsoft.com/en-us/sharepoint/dev/apis/webhooks/get-started-webhooks
I am having trouble finishing step 5. Postman always gives me this error and I am not sure why.
Troubleshooting details
If you contact your administrator, send this info to them.
Copy info to clipboard
Request Id: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Correlation Id: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Timestamp: 2022-11-18T09:34:11Z
Message: AADSTS650057: Invalid resource. The client has requested access to a resource which is not listed in the requested permissions in the client's application registration. Client app ID: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX(Postman App). Resource value from request: https://<mysite>.sharepoint.com. Resource app ID: 00000003-0000-0ff1-ce00-000000000000. List of valid resources from app registration: fe7b6ec1-3281-4dd6-8864-dff33cd1021e, 00000003-0000-0000-c000-000000000000.
Flag sign-in errors for review: Enable flagging
If you plan on getting help for this problem, enable flagging and try to reproduce the error within 20 minutes. Flagged events make diagnostics available and are raised to admin attention.
00000003-0000-0000-c000-000000000000 is Graph.
fe7b6ec1-3281-4dd6-8864-dff33cd1021e is SharePoint Online Client Extensibility Web Application Principal Helper.
In the error it says the app id (00000003-0000-0ff1-ce00-000000000000) that I am trying to use and then lists the valid resources form my app. I can add another resource to the app and it will be listed there in the error message but I do not know how to add my specific resource to the list. Does anyone know how I can do that or if that is even what I need to be doing?
I tried to reproduce the same in my environment and got the results successfully like below:
I created an Multi-Tenant Azure AD application and consented the below API permissions:
To generate the access token, I used below parameters:
Grant Type : Authorization Code
Callback URL : redirect_uri
Auth URL : https://login.microsoftonline.com/common/oauth2/authorize?resource=https://TENANT.sharepoint.com
Access Token URL : https://login.microsoftonline.com/common/oauth2/v2.0/token
Client ID : CLIENTID
Client Secret : ClientSecret
Access token successfully generated like below:
To get Documents list Id click on Use Token and execute the query like below:
GET https://XXXX.sharepoint.com/_api/web/lists/getbytitle('Documents')?$select=Title,Id

Azure WVD Rest API Auth

I have a aspnetcore app that I'm writing and would like to be able to manage WVD resources. The problem I'm having is that the Bearer token I'm getting from Msal is giving me a 401 when I try to
GET https://rdweb.wvd.microsoft.com/api/feeddiscovery/webfeeddiscovery.aspx
I thought maybe I needed to add an API permission to my app in azure, but I've already added:
https://management.azure.com/user_impersonation
And I cant seem to locate anything that suggests it might work for WVD.
Maybe I'm way off track though.
I've tried looking at the source:
https://github.com/Azure/RDS-Templates/tree/master/wvd-templates/wvd-management-ux/deploy
But its been compiled and minified, so thats proving to be difficult.
Any help getting a valid token to call the WVD Rest API would be greatly appreciated.
Getting the token:
Full Code (minus the Microsoft.Identity.Web stuff)
var token = await TokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(new[] { "https://mrs-Prod.ame.gbl/mrs-RDInfra-prod/user_impersonation" });
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://rdweb.wvd.microsoft.com/");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{token}");
var result = await httpClient.GetAsync("api/hubdiscovery/eventhubdiscovery.aspx");
result = await httpClient.GetAsync("api/feeddiscovery/webfeeddiscovery.aspx");
This method is from the Microsoft.Identity.Web project.
The https://management.azure.com is for Azure Service Management API, in your case, it is not correct.
Please navigate to the AD App in the portal -> API permissions -> APIs my organization uses -> search by Windows Virtual Desktop, find it and click.
If you want the management tool to make Windows Virtual Desktop management calls on behalf of the user who's signed into the tool, choose Delegated permissions -> user_impersonation, complete the steps like the screenshot. You can also let the user consent the permission by himself without clicking the Grant admin consent button, it depends on you.
Then the permission appears like below.
For more details, see this Tutorial: Deploy a management tool and this step.
Update:
Try to use powershell New-RdsRoleAssignment to add user account as a RDS Owner role, make sure you have installed the Microsoft.RDInfra.RDPowerShell module first, refer to this link.
Add-RdsAccount -DeploymentUrl "https://rdbroker.wvd.microsoft.com"
Get-RdsTenant
New-RdsRoleAssignment -RoleDefinitionName "RDS Owner" -SignInName "xxxx#xxxx.onmicrosoft.com" -TenantName "joywvd"
Then I run the Get-RdsTenant command again, and use fiddler to catch the request, get the token, decode in the https://jwt.io/, it appears like below.
The aud and scp should be the same as your token, you can also decode your token to check, then I use postman to call the https://rdweb.wvd.microsoft.com/api/feeddiscovery/webfeeddiscovery.aspx, it works.
Omg I just figured it out by comparing the token I got from the msft rdweb application:
From the RDWeb App:
"aud": "https://mrs-prod.ame.gbl/mrs-RDInfra-prod",
From my App:
"aud": "https://mrs-Prod.ame.gbl/mrs-RDInfra-prod",
....
Yes I was using an uppercase P in - mrs-Prod. And the msft app was using a lowercase p in mrs-prod.
I'm flabbergasted, angry and excited all at the same time.
For the record I copied my value directly from Azure in my apps api permissions screen.

AADSTS65001: The user or administrator has not consented to use the application with ID '<application ID>

We following the v2 of the OAuth2 of Microsoft Code grant flow as documented in the following,
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
After we created an application in App Register under Microsoft Azure, and try to get the code from the following url
https://login.microsoftonline.com/concept4.net/oauth2/v2.0/authorize?client_id=&response_type=code&redirect_uri=https://postman-echo.com/get&response_mode=query&scope=profile%20openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&state=skip_get_token2&prompt=consent
Then we got the following error
{"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID '' named 'c4app2019'. Send an interactive authorization request for this user and resource.\r\nTrace ID: 46424a2f-a3a2-45da-8902-888f5ca61c00\r\nCorrelation ID: 49d0a6ad-e158-4bc9-97b8-a6391c6470bb\r\nTimestamp: 2019-12-11 07:51:31Z","error_codes":[65001],"timestamp":"2019-12-11 07:51:31Z","trace_id":"46424a2f-a3a2-45da-8902-888f5ca61c00","correlation_id":"49d0a6ad-e158-4bc9-97b8-a6391c6470bb","suberror":"consent_required"}
Any idea what permission we need to grant to our application?
I can not reproduce your issue on my side. Here are my steps for your reference.
1.Create an application with User.Read and profile permissions.
2.Since the permissions I added don't need admin consent, so I can consent by the first time I login.
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=59437d85-46f8-409c-8211-b3db91a8b0e5
&response_type=code
&redirect_uri=http://localhost
&response_mode=query
&scope=https://graph.microsoft.com/User.Read
&state=12345
3.Get the token by using the code I got from step2
To locate your issue, please provide the screenshot like step2(App registrations->your application->API permissions). And the value of scope you used to get code/token.
In case it's helpful to anyone, I was running into the same problem using the magical AzureServiceTokenProvider class from the Microsoft.Azure.Services.AppAuthentication.1.3.1 package. Very simple code
var tokenProvider = new AzureServiceTokenProvider();
string token = tokenProvider.GetAccessTokenAsync("https://mytenant.onmicrosoft.com/8a0bec0f-x-x-x-x").GetAwaiter().GetResult(); // Application ID URI
My error message was
AADSTS65001: The user or administrator has not consented to use the application with ID 'd7813711-9094-4ad3-a062-cac3ec74ebe8'. Send an interactive authorization request for this user and resource.
I couldn't find this d7813711 guid anywhere in my Azure AD. After looking into how this class works in a decompiler, it turns out when you don't specify an app ID, the class defaults to this guid. Maybe this guid is valid across tenants in Azure? To fix the issue so you can get a token for your app, simply add this as an authorized client application.
[Additional test 1]
Step 1:
I have create another app the use less API permission, which has the same issue
Step 2:
Get code by the following url
https://login.microsoftonline.com/concept4.net/oauth2/v2.0/authorize?client_id=15bf7752-....-c51cd145174c&response_type=code&redirect_uri=https://postman-echo.com/get&response_mode=query&scope=https://graph.microsoft.com/User.Read&state=skip_get_token2
and got
Step 3:
It seems working
It seems that the scope in Microsoft document for getting code and token is not correct or need some additional permission.
We also had this issue. We have updated our graph client to a newer version. We have done the following steps:
Revoke all admin consent
Remove all permissions
Add removed permissions back
Grant admin consent
I hope this will help someone with troubleshooting.
I had a similar problem, following this video step by step on how to set up your App Registration in AAD and test it with Postman solved my problem (I was missing some details in the configuration), I hope this help

MS Identity Azure app registered but sends unauthorized_client in implicit flow

I have registered an app in Azure for Microsoft Identity platform. I configured it to allow MS Accounts (e.g. outlook.com) and have basically done everything in a few of the quickstarts online here and here (except for "add credentials to your web app"). I have also checked the boxes that enable implicit flow.
I redirect my React application to the URL to sign in (using implicit flow), I get to enter my username but then I see
unauthorized_client: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908
Like I mentioned above, I've gone through several quick starts and read about implicit flow here and followed their examples for my code.
I also tried just deleting the app registration and starting over. No luck.
JS Code attempting to implement Implicit Flow
JS code that redirects the browser to a Url that looks like Microsoft's first example on their implicit flow page
goSignIn() {
const tenant = 'common'; // (for us with MS accounts)
const clientId = '*****';
const redir = encodeURIComponent('http://localhost:3000/signin');
const nonce = Math.round(Math.random() * 10000, 0);
const uriTemplate = 'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?client_id={clientId}&response_type=id_token+token&redirect_uri={redirect}&scope=openid&response_mode=fragment&state={state}&nonce={nonce}';
const filledTemplate = uriTemplate
.replace('{tenant}', tenant)
.replace('{clientId', clientId)
.replace('{redirect}', redir)
.replace('{nonce}', nonce)
.replace('{state}', nonce);
console.log(filledTemplate);
window.location = filledTemplate;
}
App Configuration in Azure:
Azure -> Identity -> App Registrations -> MyApp -> Authentication
Redirect Uri: http://localhost:3000/signin (React app runs on 3000 and I have a route configured for /signin)
Not using any suggested Redirects.
Checked Implicit checkboxes for ID Token and Access Token
Live SDK support enabled
Supported account types is set to "Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com)"
Azure -> Identity -> App Registrations -> MyApp -> API Permissions
MS Graph
User.Read
Email
Profile
openid
From the docs I read, I thought I had done enough to the id token. I'm not sure what tweak must be made in order to get it to work.
I experienced an issue like this one. The mistake I made has to do with the App ID: when you create the client secret the Azure UI will present the secret and the secret ID. This secret ID is not the one to use in your app's configuration. Rather, you need the Application ID found on the Overview page.
I imagine that there are many configuration problems which can produce this error message. In general: pay close attention to the App ID, if the error is that the app is not found.
It seems that you have done enough to get the token. I have tested this on my side, it works well. Here I provide you with my screenshot for you to check again.
Also, here is my working request url, you can login with your msa to have a test.
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=5fd66168-7ba3-4bbc-a155-bff662eed9f7
&response_type=id_token+token
&redirect_uri=http://localhost:3000/signin
&scope=openid
&response_mode=fragment
&state=12345
&nonce=678910

Asking for user info anonymously Microsoft Graph

In an old application some people in my company were able to get info from Microsoft Graph without signing users in. I've tried to replicate this but I get unauthorized when trying to fetch users. I think the graph might have changed, or I'm doing something wrong in Azure when I register my app.
So in the Azure portal i have registered an application (web app), and granted it permissions to Azure ad and Microsoft graph to read all users full profiles.
Then I do a request
var client = new RestClient(string.Format("https://login.microsoftonline.com/{0}/oauth2/token", _tenant));
var request = new RestRequest();
request.Method = Method.POST;
request.AddParameter("tenant", _tenant);
request.AddParameter("client_id", _clientId);
request.AddParameter("client_secret", _secret);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("resource", "https://graph.microsoft.com");
request.AddParameter("scope", "Directory.Read.All");
I added the last row (scope) while testing. I still got a token without this but the result is same with or without it.
After I get a token I save it and do this request:
var testClient = new RestClient(string.Format("https://graph.microsoft.com/v1.0/users/{0}", "test#test.onmicrosoft.com")); //I use a real user here in my code ofc.
testRequest = new RestRequest();
testRequest.Method = Method.GET;
testRequest.AddParameter("Authorization", _token.Token);
var testResponse = testClient.Execute(testRequest);
However now I get an error saying unauthorized, Bearer access token is empty.
The errors point me to signing users in and doing the request, however I do not want to sign a user in. As far as i know this was possible before. Have Microsoft changed it to not allow anonymous requests?
If so, is it possible to not redirecting the user to a consent-page? The users are already signed in via Owin. However users may have different access and i want this app to be able to access everything from the azure ad, regardless of wich user is logged in. How is the correct way of doing this nowadays?
Or am I just missing something obvious? The app has been given access to azure and microsoft graph and an admin has granted permissions for the app.
Edit: just to clarify, i tried both "Authorization", "bearer " + _token.Token, and just _token.Token as in the snippet.
Yes, it's still possible to make requests to Graph without a user present using application permissions. You will need to have the tenant admin consent and approve your application.
Edit / answer: Adding the 'Authorization' as a header instead of a parameter did the trick. It works both with 'bearer token' and just 'token'

Resources