Gmail API Access Single User Without Domain Wide Delegation - gmail-api

We have a bit of a dilemma that we are running into with a couple applications that are trying to read a given users email without user interaction to authorize. The key to this approach is that we want no user interaction, and want to load the client server application with the proper JSON credentials downloaded from the Google Developer Console.
I have this approach working for programs where we create a service account in the Developer Console, and then delegate domain wide authority to that account with the proper scope access. However what we are hoping is that we don't have to delegate domain wide authority, and just read the users email who created this developer console project. I have tried many different types of solutions for this, but always run into the same limitation that I have to grant domain wide access.
What I am wondering is if there is any way to gain access to a single users mailbox using a server to server type approach and not have to grant domain wide access?
I appreciate your help with this issue!

There is no supported authorization flow for what you want to do. You must either use a service account that has been delegated domain-wide authority, or you must use a 3LO flow that involves user consent.

It seems you're looking for OAuth for Server to Server Application. You will also be using a service account. But, granting of domain-wide authority for service accounts is an optional thing. You don't have to enable it if you don't want to.
To support server-to-server interactions, first create a service
account for your project in the Developers Console. If you want to
access user data for users in your Google Apps domain, then delegate
domain-wide access to the service account.
Then, your application prepares to make authorized API calls by using
the service account's credentials to request an access token from the
OAuth 2.0 auth server.
Finally, your application can use the access token to call Google
APIs.

Related

Accessing GMail API using Service Account, but limited to single mailbox

I'm trying to set up a Service Account that can access the GMail API, but for security purposes I want it limited to only a single mailbox (I don't want the development team to have full access to all mailboxes in the organization.)
My understanding of how Google handles service accounts and permissions is limited. I can't seem to find specific details about how this would be set up. I have set up a service account with client ID and secret. And I have associated that with an API client that has the GMail read-only scope. But how does that get associated with a specific mailbox? I do see a setting that allows "domain wide delegation", which seems concerning.
Maybe I'm just not understanding this correctly, but does that mean this service account can now read the contents of all mailboxes in the GSuite account?
How do I make sure this service account is limited to the one mailbox I want it to access?
I think you are talking about user impersonation using the service account. I am afraid that it is not possible to limit the access that the service account can have. The only possible limitations is related to the creations of credentials on the project and things like that, but if a service account has domain wide delegation to do user impersonation, then it is not possible to set up limitations to it.
You can find more info about the possible limitations here https://cloud.google.com/resource-manager/docs/organization-policy/restricting-service-accounts

Why do I need two AAD applications just to add roles into an access token?

As shown by many samples I have two AAD application registrations, one for my javascript-based front end, and one for my JSON-only web APIs.
If I fully trust my client AAD application, why does AAD require me to create a second AAD application for my web APIs?
For example, assuming I add specific roles to my client AAD application, if client signs in with AAD and gets an id token and access token containing my roles, it only needs to send the access token to my APIs. The API only needs to crack the JWT, validate the audience, issuer, tenant, roles permissions, and signature. In this world, no client secret is needed in the web APIs, a second AAD application registration not needed, and still no call to AAD from my APIs. Unfortunately, without two AAD applications, I cannot figure out a way to have AAD include roles into my access token.
If I didn't fully trust the issuer from mucking with claims, I can see why I would need two AAD applications and a client secret. But since I do trust my AAD application and the signature of the JWT, why the extra complexity? Or maybe there is a way to do this that I haven't found?
Thanks!
Responding to Marc here because just not enough characters in the comments field -- The sample you referenced is an excellent sample, specifically the JavaScript one calling the Web API. It is what I am doing right now in fact. However, the problem is that Web API in the sample is open to anybody who has authenticated on the tenant. I need to secure the Web API down to certain individuals in the tenant, and simply checking the client/app id is not sufficient as anybody who can create an AAD app can fake it.
So what I need to do is have roles added to the the access token so I know that my application authenticated the user, and that user has been granted the required roles. For example, here is a Microsoft sample. And even here a Microsoft video walking through the process.
If I don't have two AAD applications w/client secret, the roles claims is never provided in the access token. It is always provided in the id token, but not the access token.
I feel like I am missing something obvious here. If AAD would just put the roles I requested into the JWT when I authenticated against it, and I validated its signature, audience, issuer, and roles, I wouldn't need any of this extra complexity?
Ah, I think I understand where you are going: you would like to control which users can access an API, no matter what client app they are using to access the API with. That's a function of the API - you cannot control that through AAD. In AAD you can control which users can access which applications (UI) using either user access restrictions (enterprise tab) or role-based access. However, access to an API is controlled in AAD at the calling application level via scopes. APIs are never accessed directly by users but only by other apps so controlling access permissions at user level would cause admin havoc. So, you can control what permissions a user has in the app they are using and you can control what permissions that application (client) has in other applications (APIs, resource servers) it is using.
In other words: role is about user access to UI, scope is about one apps' access to another.
App secrets provide added security for getting tokens - they have no bearing on what permissions are included in the token.
Can you provide a link showing that two apps are needed? That should only be the case if the API you want to call is not provided by the web app which served the JS to the browser. None of the 'official' samples require you to register two apps (Graph API, used in some of these samples is a separate API and it is already registered). A problem with tokens passed from the browser is that they were acquired by a public client, not using any secrets apart from user creds. Therefore, they are easier to steal and re-use. Your own back-end app may want to use a secret to get its own token (extension grant) to call yet another API using a token that does not reside in a public client.

Security Around Microsoft Azure AD AD "Application Access"

I have successfully configured qn Azure AD App Registration, allowing a client_credentials based OAuth 2.0 flow to work. This allows a third party application to access Microsoft Graph API. The app has "Calendar.Read" permission. Meaning the app can pretty much read any of the calendars (including CEO's).
I now have a conversation with security. What is out there in the Microsoft world, that I can use to lock down usage of API access via this Application Permission? Is there ability to do things like:
Restrict IP ranges the App can be accessed from?
Restrict users that can access the App? (However in Client_credentials, there is no user context)
Log traffic / activity happening via the App?
The only thing i can think of now is to say the Redirect URL configuration on the app means, no other application can get an access token using the Client_credentials, even if the application id & passkey get compromised
Any advice on further security controls that can be put in place?
Restricting access: You would need to do this in your application. The Client Credential flow doesn't allow for restricting what users as you point out. However there is nothing stopping you from adding user authentication to your application, possibly using a delegated graph auth flow to determine who they are.
IP Ranges: This is not possible currently.
Logging Traffic: This is not possible on the graph side currently, however you could/should log traffic on your applications side.
Redirect urls will not help you because they are not used int eh client credential flow.
In general application only auth (client credential flow) + a broad authorization scope is very powerful, but must be managed correctly. You don't inadvertently want to build a totally new users/permissions model over the top of the graph :)
There are very few options available currently available to offer these controls at token issuance (in Azure AD) or at API access (in Microsoft Graph). However, you can achieve similar results by carefully managing access to the app's credentials. Here are a couple steps you can take (not exhaustive):
App credentials: keep them secret, keep them safe
Use Key Vault. You can configure many of the restrictions you mention for access to data in Key Vault, including IP ranges and which users access. Key Vault also offers auditing of access to secrets. Don't forget to also be careful about which users have management access to the Key Vault (e.g. other users with access to the same Azure subscription).
Use certificates (public/private key pair), rather than client secrets (passwords), to authenticate the app. People tend to manage certificates much more carefully than they manage shared passwords, and developers are much less likely to hard-code the secret into scripts/code.
Be careful and deliberate about which users can manage the app's credentials
This is often overlooked. A user (or another app) who can access existing credentials, or add a new authorized credential to an app can act as the app and (mis)use all the permissions the app has been granted. This includes:
Users (and apps) in the "Company Administrator", "Application Administrator" and "Cloud Application Administrator" directory roles.
Users who are set as owners of the app registration (Application object) and enterprise app (ServicePrincipal object) for the app.
Users (or systems) who have access to the server or service the application resides on (which will have, or have access to, the credentials).
For all of these cases, ensure this is the smallest possible number of users, and they actually have a legitimate need. For users who do need access, wherever possible enforce just-in-time, time-limited access (not persistent access), such as with Azure AD Privileged Identity Management, for time-bound, just-in-time access for Azure AD directory roles and Azure resources.

Authentication flow Service to Service Microsoft Graph and Bookings API

I am building a custom mobile application that has a client, custom backend server (I'm building) and interacts with numerous other api's. One of these api's is Microsoft bookings.
The problem I'm facing is I need to be authenticated via server to server, with a shared client secret. I'm aware of the numerous docs from MS but have yet to find a solution. I'm wondering if Server to server is even possible with Bookings.
I am able to get an access_token server to server with these permissions. (I have granted 'all permissions' to this app in Azure AD already).
"roles": [
"Calls.JoinGroupCall.All",
"OnlineMeetings.Read.All",
"OnlineMeetings.ReadWrite.All",
"Application.ReadWrite.OwnedBy",
"Calendars.Read",
"People.Read.All",
"Application.ReadWrite.All",
"Calls.InitiateGroupCall.All",
"Directory.ReadWrite.All",
"Calls.JoinGroupCallAsGuest.All",
"Sites.Read.All",
"Sites.ReadWrite.All",
"Sites.Manage.All",
"Files.ReadWrite.All",
"Directory.Read.All",
"User.Read.All",
"Calendars.ReadWrite",
"Mail.Send",
"ProgramControl.Read.All",
"ProgramControl.ReadWrite.All",
"Calls.Initiate.All"
],
Those are the permissions from the decoded token. When I go to make calls to the Bookings api I receive 401.
I can however use this token to access different graph endpoints no problem.
I will note, that I am able to make successful calls to the bookings api through Graph Explorer with my account, not related to this 'Application in Azure AD'.
Does this resource in Azure AD need a bookings License?
Is this even possible S2S?
Are there any other ways to bypass this without user credentials?
Thanks.
So I spent over a week trying to solve this problem due to the MS doc nightmare. I'm only posting to help others!
Bookings doesn't support service to service yet. So if you wan't to implement this without a user physically signing in, IE. If you have a dedicated booking admin account credentials you have to hard code the clients credentials.
I found my answer here https://stackoverflow.com/a/49814924/9105626
Microsoft Bookings API doesn't seem to support "Application Permissions" so far.
Only permissions available are "Delegated Permissions", which means your token has to be acquired with the context of a signed-in user.
Here are two Microsoft documentation sources that I came across:
Microsoft Graph Permissions Reference - Please look at the "Bookings Permissions" section.
Microsoft Bookings Samples
I know you mention Server to Server authentication using a client secret. AFAIK, that case will NOT work directly, because clientId and clientSecret only provide an application's identity (which can't be assigned any permissions because there are no relevant application permissions available for this API).
Just in case you can have some User context involved, here is code from bookings samples link above, to acquire the token in a Native application using ADAL
var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/common/");
var authenticationResult = await authenticationContext.AcquireTokenAsync(
"https://graph.microsoft.com/",
clientApplication_ClientId,
clientApplication_RedirectUri,
new PlatformParameters(PromptBehavior.RefreshSession));
// The results of this call are sent as the Authorization header of each HTTPS request to Graph.
var authorizationHeader = authenticationResult.CreateAuthorizationHeader();
Suggestions on ways to make this scenario work
On Behalf Of Flow
Your mobile application client could prompt a user for credentials to act on Behalf of the user and call your backend web API, which in turn calls the downstream API like Bookings API. This is called Service to Service Calls on behalf of the User
Here is a code sample which shows exactly this with a native application (WPF) and an SPA. In your case, just replace the WPF application with your mobile client application for understanding purposes and rest of the scenario becomes very similar.
Calling a downstream web API from a web API using Azure AD
ROPC Grant (Not Recommended)
Resource Owner Password Credentials grant can help as your application will have end user password available to it, but it has multiple issues and any security guidance will discourage you from using it.
ROPC opens up security risks, doesn't follow best practices and has functionality issues as well. ROPC doesn't work with MFA enabled users as well as federated authentication users.
For all practical purposes, you should avoid ROPC as long as possible. You can find the same recommendation in ADAL documentation itself and multiple other documentations from Microsoft or even generally about OAuth 2.0.

Programmatic (API calls) User Authentication using Azure AD B2C instead of login.microsoftoneline.com form

New to Azure AD... So please don't be too harsh if this is off target. :-)
Technology Stack - Latest Angular 2 with C# Middle tier and latest .Net Framework.
Ideally, What we want to do is use Azure AD B2C to store user credentials and to do the authentication - but we want our 'own' forms on our site to do the login Forms capture and logging - then pass the credentials through an API (REST?) Call (using MS Graph SDK?) to Azure AD B2C and then check the call return for the Authorization content message.
Couple of reasons - control of the application flow, Logging and the "flickering of the URL" (i.e. going from our site URL to login.microsoft... URL and then back to our sites URL).
Is this doable without doing a hack?
Thank you in advance for your help and patience!
You are looking for the "Resource Owner Password Credentials".
This is not currently supported for Azure AD B2C, but you can give user feedback to the B2C team that you want this through the Azure Feedback Forum: Add support for Resource Owner Password Credentials flow in Azure AD B2C and headless authentication in Microsoft Authentication Library
You should also see updates at that location if and when they implement this feature.
The resource owner password credentials flow is now in preview.
In Azure Active Directory (Azure AD) B2C, the following options are
supported:
Native Client: User interaction during authentication happens when
code runs on a user-side device. The device can be a mobile
application that's running in a native operating system, such as
Android, or running in a browser, such as JavaScript.
Public client flow: Only user credentials, gathered by an application, are sent in
the API call. The credentials of the application are not sent.
Add new claims: The ID token contents can be changed to add new claims.
The following flows are not supported:
Server-to-server: The identity protection system needs a reliable IP
address gathered from the caller (the native client) as part of the
interaction. In a server-side API call, only the server’s IP address
is used. If a dynamic threshold of failed authentications is exceeded,
the identity protection system may identify a repeated IP address as
an attacker.
Confidential client flow: The application client ID is
validated, but the application secret is not validated.
From here.
Note that one disadvantage of doing what you're requesting is precisely that you can do "login forms capture and logging", so your application has a chance to see the credentials and perhaps take copies of them; thus your users have to trust you to behave.
The normal web-based flow means that your application doesn't need to be trusted; it never even sees the password at all.

Resources