B2B with Microsoft Graph - azure

As you probably know, I am creating a multi-tenant azure application, which is using the B2B functionallity.
I am testing the B2B functionality and after some research I got a working sample.
Small summary: User authenticates against common authority, first token is acquired via common authority with the authorization code and from then, everytime I need a service client, I try to obtain those tokens from the 'current tenants' authority.
When I request 'Me', it only works against the home tenant. When I request me with a trusted tenant, I got an error that my user identifier does not exist in the directory. Probably because user does not actually exist in the trusted tenant.
When I request Users, it works fine. I can get both, home tenant users and trusted tenant users.
Is this normal behaviour?
Is this something I need to handle programmatically or would this been solved by using the AD graph?
(So when I know I need user info, just query the home tenant?)
Or is this a bug?
Any thoughts on this would be greatly appreciated!

Guests added to a directory via the B2B Collaboration feature will not work correctly on multi-tenant apps or the Microsoft Graph if you're using the common endpoint.
The common endpoint will always authenticate the user against his/her home tenant, not against any tenant where (s)he is a guest.
In order to successfully query /me for a guest, you'll need to have them sign-in through the tenant specific endpoint for the tenant where they're a guest.
See my answer to this other post for a more in-depth explanation / context:
Can users from an unmanaged Azure AD directory, sign into an Azure AD multi-tenant application which resides in a different directory?

I have noticed that when you want to switch between tenants, you need to re-authorize against the current tenant.
I got it working this way:
1. First sign-in needs to be done against the common endpoint.
2. Every time I need a token for certain resource, I try to get the token silently.
=> This can throw 2 different AdalSilentTokenAcquisitionException
Nothing found in cache, also no refresh token found
=> In this case, I redirect the user to the login page again.
When you switch between tenants, and it is the first time you want to login using a tenant where you've been trusted, you can get a error like: User or admin should be given consent for this application. Although the admin from his home tenant has added the application in the directory for the home tenant. Anyone who knows why this consent is needed? So tenant A and tenant B admins have both been given consent. Why does a trusted user from B in A still needs to consent someway?
I was able to trigger the consent flow by redirecting the user to the authorization request URL.
So when I got an AdalSilentTokenAcquisitionException, and the error code is "failed_to_acquire_token_silently" then I had to redirect the user to the URL generated by the authContext (authenticationContext.GetAuthorizationRequestUrlAsync) when the cache had been cleared, no refresh token will be found, then redirect the user to resign.

Related

Web app with Azure AD SSO: Is it possible to give users from an external tenant access to their email?

I have an application registered in Azure Active Directory. I use this app registration to provide a simple SSO implementation for my web application. Users go to my application, choose SSO for authentication, redirect to the login.microsoft.com page, then get sent back with the proper codes. No sweat.
The SSO part is not issue inside or outside of my tenant. I've been able to get the proper flow setup and if users are permitted access, they can login with their Microsoft account and access my application.
Email, however, is turning out to be a real issue.
Internal users in my tenant are not a problem at all. Once I get the JWT from Microsoft, I can request an access token for Graph, send emails, create drafts, delete, etc. There is no issue here.
The problem comes up when I have a user in an external tenant. They can login just fine and get a code from Microsoft, but email doesn't work. I started researching a multitenant solution with the Graph API and made some progress there. I was able to change how they request their tokens using 'client_credentials' and got the appropriate delegated app permissions set up but those permissions allow the external tenant to send emails as though they were users in my tenant. Which obviously I don't want.
I have the external users setup as guest users in my tenant. I've even gone so far as to put an Exchange Online license on the guest users account.
This is the latest error I've received:
[error] => Array
(
[code] => ResourceNotFound
[message] => Resource could not be discovered.
[innerError] => Array
(
[date] => 2021-08-09T16:08:41
[request-id] => 76d9c8ad-e2fd-4286-a8d7-5a3bb4ff3ba8
[client-request-id] => 76d9c8ad-e2fd-4286-a8d7-5a3bb4ff3ba8
)
)
I get this when I put the external user's object ID in the request for the sendMail method of the Graph API. If I put an internal user's object ID into that request, the external user can login, get a token, and send mail as that internal user just fine.
So my question is, is this even possible? Can a user in an external tenant login to my app using Azure AD SSO and also have access to send mail from their account within my application? If so, how far off base am I with my implementation?
As it is a multi-tenant application that supports SSO for external users.
As per Dev's Comment,
Not sure in your scenario, you're using Azure AD B2C (not sure it suits your scenario) or B2B and try to simulate accessing multiple mailboxes
Identity Providers for External Identities
External Guest users with personal MS Account can redeem your B2B collaboration invitations.
During Self Service sign-up user flow, personal MSA can be added as one of the Identity Provider.
No Additional Configuration required to make this identity provider available for user flows.
Email one-time passcode: When redeeming an invitation or accessing a shared resource, a guest user can request a temporary code, which is sent to their email address. Then they enter this code to continue signing in.
Email one-time passcode feature authenticates B2B guest users when they can't be authenticated through other means.
When setting up a self-service sign-up user flow, you can add Email One-Time Passcode as one of the allowed identity providers.
Reference link:
Identity providers for External Identities - Azure AD | Microsoft Docs
B2B Collaboration - Understand user tokens in B2B collaboration - Azure AD | Microsoft Docs

Identical Azure apps do not work in different tenants

I use Azure apps to sign users in to a web app and a desktop app. I also query for user information via Microsoft Graphs /user/ endpoint.
So we have to apps registered in Azure; one is a web app / api with permissions to sign users in and read all user profiles from graph. The other is a native app with permissions to the first app, and permissions to sign users in.
In one tenant, this works fine. However in the other tenant the web api har permissions to sign users in, but Graph declines access to the /users/ endpoint due to insufficient privileges. The error is: Authorization_RequestDenied, Insufficient privileges to complete the operation.
However the exact same privileges work fine in another tenant. In the faulty tenant we get a token from graph but when we use the token on the user endpoint it throws the insufficient priv. error.
Signing in users via the desktop app (we use owin) works in one tenant but in the faulty one it sais that app tenant.onmicrosoft.com/guid does not exist in tenant.onmicrosoft.com
The app uri is correct in the settings and the app has the same privileges in both tenants.
We tried recreating the apps since this has solved similiar issues when developing things like this before. This time it doesnt seem to work however. Now I'm at my wits end here. Could there be some other issue blocking here?
The faulty tenant is part of a multi-tenant. However we only poll for users in one tenant as of now.
The apps have also been given consent by an admin via the azure portal. What am I missing here? How should i proceed with trying to fix this error?
Edit: I added a new directory in my tenant and it does not work in this new directory. Same error as with our clients tenant.
Working token for directory A:
eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFBQUFDNXVuYTBFVUZnVElGOEVsYXh0V2pUQkVOV21GUUgtZjRGS0VjYlIwU3Y1NndrdzhvSjhjbDIwX3JtZEJBc2h6eDhKT2VNZjFEbVFjNm1GUUdxZ2VSRFJZMTEzNXE3ZXJkTjlHTFZ6T3NycnlBQSIsImFsZyI6IlJTMjU2IiwieDV0IjoiaTZsR2szRlp6eFJjVWIyQzNuRVE3c3lISmxZIiwia2lkIjoiaTZsR2szRlp6eFJjVWIyQzNuRVE3c3lISmxZIn0.eyJhdWQiOiJodHRwczovL2dyYXBoLm1pY3Jvc29mdC5jb20iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC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5b6ArfjxTmeDR82XTmYw51n2YAbWl2q8R58dqELOguddwnKkBBCiMwKsD_UvG2oX_M9ZMy-Lc8lERduolyST7D0BZSoYCNe9f0j85AXIOgXr_yMA5MrVz7qSVFKZ1if2BR9YvvMCphW2uQCrebEJAnchyxHiCb5refnhm2sfsDBRJqd5NWwK0-a956a6dC2zg59JbW55-3wezQOfXKYzC5ybzO7l1hV41EnJ4atBW6EvR2er7WyCAFb1Y1hSB_wgZSo7pC4LnQRRm9KXq-x2aSRKiUSg265K0RQ
You need to receive Admin Consent for an administrator of the tenant. I'm assuming that because this happens when hitting /users, you've requested either User.Read.All or User.ReadWrite.All. Both of these require Admin Consent before a normal user can authenticate and provide User Consent.
I wrote an article a while back that you might find this helpful here: User vs Admin Consent. The examples target the v2 Endpoint while it sounds like you're using v1. That said, the same consent models and workflow apply to both v1 and v2.

Azure AD B2C - Sign out a user from all sessions

I have 3 websites using a single B2C tenant. I have been asked to set it up so that when a user signs out of one website, sign out of them all.
Likewise if their account is deleted.
I thought that I would have to introduce a call to Azure on every request to determine if the user is still logged in, but as far as I can see, there isn't a Graph API endpoint that would allow me to determine the user status.
Am I thinking about this the wrong way? Is there a way to do this easily using B2C, Graph API, the Active Directory client etc.?
Maybe there is an option when setting up the OpenIdConnectAuthenticationOptions for example.
According the description on Azure Document:
While directing the user to the end_session_endpoint will clear some of the user's single sign-on state with Azure AD B2C, it will not sign the user out of the user's social identity provider (IDP) session. If the user selects the same IDP during a subsequent sign-in, they will be reauthenticated, without entering their credentials. If a user wants to sign out of your B2C application, it does not necessarily mean they want to sign out of their Facebook account entirely. However, in the case of local accounts, the user's session will be ended properly.
So you can directly use the end_session_endpoint. You can find it in the metadata document for the b2c_1_sign_in policy endpoint, e.g.:
https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=b2c_1_sign_in
You can refer to Azure Active Directory B2C: Web sign-in with OpenID Connect for more info.
Any further concern, please feel free to let me know.
I might be late. But if that helps. A.c to docs
When you redirect the user to the Azure AD B2C sign-out endpoint (for both OAuth2 and SAML protocols), Azure AD B2C clears the user's session from the browser. However, the user might still be signed in to other applications that use Azure AD B2C for authentication. To enable those applications to sign the user out simultaneously, Azure AD B2C sends an HTTP GET request to the registered LogoutUrl of all the applications that the user is currently signed in to.
Applications must respond to this request by clearing any session that identifies the user and returning a 200 response. If you want to support single sign-out in your application, you must implement a LogoutUrl in your application's code.
This is called single sign out .
Please refer to https://learn.microsoft.com/en-us/azure/active-directory-b2c/session-overview#single-sign-out
Microsoft has an API for this by now. I link to the following blog, as the documentation is currently wrong.
microsoft developer blog: revokeSignInSessions & invalidateAllRefreshTokens
Request
POST https://graph.microsoft.com/beta/users/{id}/revokeSignInSessions
Response
HTTP/1.1 204 No Content

Azure AD with prompt=none shows Bad Request when user is logged in into another tenant

We have an application that supports seamless login with our Azure AD tenant account via OpenID Connect implicit flow. If user is authorized to access the app providing Azure AD issued evidence - access will be granted automatically, otherwise we show regular application login screen.
Every time when user authentication is required we redirect the user to the Azure AD login page (https://login.microsoftonline.com/xyz) specifying prompt=none.
Respecting the ODIC specification such flag should have the following effect.
The Authorization Server MUST NOT display any authentication or
consent user interface pages. An error is returned if an End-User is
not already authenticated or the Client does not have pre-configured
consent for the requested Claims or does not fulfill other conditions
for processing the request. The error code will typically be
login_required, interaction_required. This can be used as a method to
check for existing authentication and/or consent.
It generally works as expected, however, there is a case where Azure AD login page will show an error screen to the End User and it happens when User logged into another Azure AD tenant.
User account '...' from identity provider
'https://sts.windows.net/.../' does
not exist in tenant '...' and cannot access the
application '...' 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.
The questions are:
Does not it violate the ODIC specification?
How to properly handle such cases in seamless for users fashion? (app is not in charge of what is going on after redirect to Azure AD).
Though I also agree that this is a violation of the spec, can I offer a workaround?
I believe you can try specifying domain_hint or login_hint parameter as well to help the system determine valid session. Hope it would give you the right answer regardless of which session user is signed in at the moment.
Yes, this is a violation of the OIDC spec. We have created a bug.
If the error is only occurring because the STS is selecting the wrong session, you could use login_hint or domain_hint to help the STS select the right session.
Yes, that is in violation of the spec and defeats the purpose of prompt=none since the the application can't keep control of the user experience anymore. #vibronet may be able to set the record straight on MS side.

How do I add users to tenant via the Graph API?

I've utilized the Partner Center REST API to provision tenants with orders/subscriptions. Now I want to start configuring the domains and users for the tenant I just created. My first step was to get a list of users using the Graph API https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations as a test expecting to see the admin account. If I pass in the domain of the reseller account in the request URL, it shows me the reseller users. But when I put in the domain of the account I just provisioned, I get Invalid domain name in the request url. I'm using the resellers AD token to do this. I'm confused as it gives me the option to specify a domain, but I can only access my own.
What credentials am I supposed to be using here? I tried to use the user/pass that was generated for the admin account from the provision, but I get unauthorized_client when trying to get an AD token from the Graph API.
It is hard to directly address your issues here since they are a little broad, and I would need more specific details about the various tenants you are working with, how your app is provisioned, permissions your app has etc...
However I think there a few principals you can follow which may help you debug your issues.
All AAD Authentication happens within the context of a specific tenant. This means whenever you get an access token for a resource, the scope of that token is limited to the boundaries of the tenant.
To authenticate with a client application in the context of a tenant, you must have the app registered in the tenant you are trying to access (line of business application / single tenant) or you have to make the app multi-tenant, in which case your app should be able to function in the context of any tenant... if the right provisioning has occurred.
Every tenant where your app is trying to function must have a service principal for the application provisioned in the tenant. This service principal represents your application's identity in the context of that tenant, and acts as a place to store the permission your application has in the context of that tenant. Most normally, this service principal gets provisioned into a tenant after a user from that tenant has consented to use the app as a part of the login experience.
If you are trying to use user context (authorization code grant flow) to retrieve details about a tenant, you must ensure that that user is present in the directory you are trying to query. For example a user U can exist in their home tenant T1. If you try to query another tenant T2 using that user account, you will get any number of errors describing that the user account does not exist etc. You can remedy this by creating a guest account for U in T2, in which case there will be a brand new user object created in T2 which links to the original user object in T1. None the less, the user object should always be present in the tenant you are trying to query.
If you are trying to sign into an application with a user account that is in T1 and T2, you need to be sure to specify the tenant you want to actually get the token for. By default, if you use the common endpoint, you will get a token for the users home tenant. However, it is perfectly valid to get a token for the secondary tenant, as long as you specify that to our Token Service when making the request.
Finally the client application you use to make these requests needs to have the right permissions to the Graph API if you want to make specific calls to the Graph API. Every tenant needs to individually consent to the application in their tenant context in order to provision the correct permissions to their application.
With those principals in mind:
The error you are getting with "unauthorized_client" seems to be an issue with application provisioning in the secondary tenant. Please make sure to first login to the application with a user from the secondary tenant, and make sure that user has the correct permissions to consent to your app (a tenant admin is best here).
For the second issue with "Invalid domain name in the request url" please try using some hints here.
Specifically this:
By using the myOrganization alias. This alias is only available when using OAuth Authorization Code Grant type (3-legged) authentication; that is, when using a delegated permission scope. The alias is not case sensitive. It replaces the object ID or tenant domain in the URL. When the alias is used, Graph API derives the tenant from the claims presented in the token attached to the request. The following URL shows how to address the users resource collection of a tenant using this alias:
https://graph.windows.net/myorganization/users?api-version=1.6.
I hope this puts you on the correct path to resolve most of your issues.
There are issues with sandbox accounts and Azure. Access to the Azure Management Portal for the sandbox isn't straightforward and at this time does not work properly. I had to create a free Azure account with my hotmail account, then link AD from the new account to my sandbox AD to bypass the bug. When adding a new directory to the new Azure account, select "Use existing directory", sign out, then sign into the sandbox account you want to link it to. Then create your app from the new account.
After getting my app setup properly and new credentials, I had to enable pre-consent with the instructions listed at the end of: https://github.com/Microsoft/Partner-Center-Explorer
Lastly, I had to login to the Graph API with the customers ID, but with the resellers credentials.
The scenarios on the Partner Center SDK website include a section "Manage user accounts and assign licenses" under the "Manage customer accounts" section.
These samples include creating users and assigning licenses and a link to a console test app.
As an aside, a new version of the Partner Center SDK has just become available here. It was released on July 5th. While there is no official change history that I can find, I can see that it includes some new classes such as CustomerUser. You may find it easier to use that library rather than hitting the REST API (depending on how much work you've already done).

Resources