Azure AD App Registration - Exchange API - Read Calendar - microsoft-graph-api

I have the following permissions granted in my Azure AD App:
App:
Read calendars in all mailboxes
Read and write calendars in all mailboxes
Read calendars in all mailboxes
Delegated:
Read user and shared calendars
Read and write user and shared calendars
Read and write user calendars
Read user calendars
Read and write user and shared calendars
Read user and shared calendars
Registration Screen Shot
I am successfully generating an Access Token like the following:
const string clientId = "my-client-id";
const string clientSecret = "my-secret"; // C
var tenant = "mytenant.onmicrosoft.com";
var authContext = new AuthenticationContext($"https://login.windows.net/{tenant}/oauth2/token");
var credentials = new ClientCredential(clientId, clientSecret);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);
With that Access Token, I am trying to make a basic request to /CalendarView passing the Bearer token header:
https://outlook.office.com/api/v2.0/users/my#email.com/calendarview?startDateTime=2017-11-12&endDateTime=2017-11-13
However, I keep receiving Access Denied. Are there additional permissions I need to set? Am I calling into the correct endpoint?

You don't include the body of the error response, but my guess is that you're hitting this because Exchange won't accept a token generated with a shared secret. Instead, you need to use a certificate-based assertion to request the token. Azure documents this a "Second case: Access token request with a certificate" here.

I actually was able to figure this out. Instead of using the Exchange API, I just applied the permissions in the Graph API.
Hit the following endpoint:
https://graph.microsoft.com/v1.0/users/{email}/calendarview?startDateTime={startDate}&endDateTime={endDate}
It's not very clear the difference between which API to use... but I'm moving forward now.

Related

Microsoft Graph - Access Deneined when accessing to calendar events with specifiying user

I am working on creating application which uses Microsoft Graph API to access to calendar events for the users that belongs to an organization.
There is no issue getting event using below endpoint
https://graph.microsoft.com/v1.0/me/calendar/events
However, when accessing to below end point cause 403 error.
https://graph.microsoft.com/v1.0/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/calendar/events
403 - Forbidden
{"error":{"code":"ErrorAccessDenied","message":"Access is denied. Check credentials and try again."}}
So far I have below:
Application is registed to Aure with granting
Application.ReadWrite.All
Calendars.ReadWrite
offline_access
User.ReadWrite.All
Have logic to retrieve the access / refresh token.
When the access token is decoded, below scoes are availalbe
"scp": "Application.ReadWrite.All Calendars.ReadWrite User.ReadWrite.All profile openid email"
Others:
Below endpoints work
https://graph.microsoft.com/v1.0/users
https://graph.microsoft.com/v1.0/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Below endpoints errors with access denied
https://graph.microsoft.com/v1.0/users/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/calendars
I also tried using User Principal Name instead of ID but it didn't make any difference.
Can someone please help why I am not able to access to the user calendar / events when specifying the user?
Error message showed Access is denied, we can understand that your account doesn't have enough permission to call that api(querying others' calendar events). Since the request calling only related with the access token, no matter whether you have an admin role or not. So let's assume whether you want other users to sign in your app and then they are able to query your calendar events.
According to your description, your token contained scp claim, so I'm sure you are using the delegate permission, which means you signed in and calling api on behalf yourself. And this may be the reason why the access is denied.
We can see the permissions in the screenshot above, I think the application permission type can solve your issue. Using permission type means the api calling is executed by your application itself, but not on behalf of some user. So the application can query any users' calendar events in your tenant.
Using application permission required you to assign application api permission like screenshot below.
Then if you are just testing via tools like postman, using request below to generate access token:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret=sampleCredentia1s
&grant_type=client_credentials
If are composing an asp.net core application and trying to call graph api via graph sdk, follow code snippet below:
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "aad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var events = await graphClient.Users["{user_id}"].Events
.Request()
.Header("Prefer","outlook.timezone=\"Pacific Standard Time\"")
.GetAsync();
Whenever you are trying to access another user calendar events, make sure you have Calendars.Read delegated permission , you can check what type of permission you have in azure portal -
https://learn.microsoft.com/en-us/graph/migrate-azure-ad-graph-configure-permissions?tabs=http%2Cupdatepermissions-azureadgraph-powershell

Obtaining user's email using Apple's IdentityToken

On my mobile app I use apple-id authorization. My implementation uses ASAuthorizationAppleIdProvider class and does not require additional proxy web-application, that sends request to Apple. All interaction is done on the mobile client.
All things work ok, and I get authorized and I get IdentityToken from Apple.
Now, I want to send this IdentityToken (looks like "AjzN91mNajN3401jazOs001m3ks") to the server. And on the server side I want to extract user's email from this token.
For Google to solve the same task I have to send GET request with token, like that
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=google_token
and if token is valid in response I get JSON with user's email inside.
How can I do the same for the Apple using Apple's identity key?
Update #1:
My project has 2 parts, client part (frontend) and server part (backend).
The functionality to obtain IdentityToken looks like that (AuthManager is just a delegate):
var provider = new ASAuthorizationAppleIdProvider();
var req = provider.CreateRequest();
authManager = new AuthManager(UIApplication.SharedApplication.KeyWindow);
req.RequestedScopes = new[] {
ASAuthorizationScope.FullName,
ASAuthorizationScope.Email
};
var controller = new ASAuthorizationController(new[] {
req
}) {
Delegate = authManager,
PresentationContextProvider = authManager
};
controller.PerformRequests();
ASAuthorizationAppleIdCredential credentials = await authManager.Credentials;
When I get credentials, there is credentials.IdentityToken property available.
Now, I want to send this identity token to the server, to let the server check this token and obtain user's email using this token from the Apple server, like I do for Google (described above).
And I do not understand, how can I do that.
What Apple endpoint and what HTTP request (GET, POST) should be used to achieve this task?
In OpenID Connect, the Identity Token is never sent to the Provider. I think this is just a typo/naming issue and you mean the Access Token.
The end result of the user authenticating is two tokens:
the Access Token, an opaque token which is not meant to be introspected by the Client. It may or may not be a JWT.
an ID Token, a JWT which contains the user claims.
To obtain the user's email address, decode the ID/Identity Token's JWT payload. To do this in Swift, see these SO answers. The JWT should contain an email value. It looks like the email address may also be an instance property of ASAuthorizationAppleIdProvider, so you should be able to get them from credentials.email.
There does not appear to be a way to directly validate the Access Token. Most OpenID Connect Providers offer a Userinfo Endpoint, or a Token Instrospection Endpoint (I think this is the Google endpoint that was linked in question), but Apple does not. A number of steps were already performed to obtain the Access Token, however, which should make it impossible to forge. If you really only want the email address, though, JWTs are cryptographically signed, so verifying the JWT should guarantee it was issued by Apple. You can also verify the Refresh Token as shown in Apple Developer docs. In your code above, I don't see a way to access Refresh Token, but if you followed an alternative flow as shown in one of the tutorials here or here, you would be able to.

Microsoft Graph API returning 403 to any request

I'm working on an application that, in this point, will retrieve the Office Groups that the logged in user is included and perform actions based on that info.
I'm using oAuth2.0 and the v2.0 token endpoint to get access without a user, and with the code below, I can provide administrator consent to the permissions (which were applied to the application permissions on the new Application Registration Portal https://apps.dev.microsoft.com/ and appear on the Enterprise Applications section on Azure), request the token to Azure and receive it, but even with the permissions applied and that token, I get a 403 response code (Insufficient privileges) from the Graph API to any request I try to perform.
The code for those actions is the following:
// Request Admin Consent
HttpRequestMessage adminConsentRequest = new HttpRequestMessage(HttpMethod.Get, "https://login.microsoftonline.com/" + TenantId + "/adminconsent?client_id="+ClientId+"&redirect_uri=https%3A%2F%2Flocalhost%3A44369%2FHome%2F");
var adminConsentResponse = await client.SendAsync(adminConsentRequest);
// Request Token
HttpRequestMessage tokenRequest = new HttpRequestMessage(HttpMethod.Post, "https://login.microsoftonline.com/"+TenantId+"/oauth2/v2.0/token") { Content = new FormUrlEncodedContent(tokenRequestPairs) };
var tokenResponse = await client.SendAsync(tokenRequest);
string tokenResponseBody = await tokenResponse.Content.ReadAsStringAsync();
var deserializedTokenResponse = (JObject)JsonConvert.DeserializeObject(tokenResponseBody);
string accessToken = deserializedTokenResponse["access_token"].Value<string>();
// Call Microsoft Graph API
HttpRequestMessage graphRequest = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/memberOf");
graphRequest.Headers.Add("Authorization", "Bearer "+accessToken);
var graphResponse = await client.SendAsync(graphRequest);
string graphResponseBody = await graphResponse.Content.ReadAsStringAsync();
var deserializedGraphResponse = (JObject)JsonConvert.DeserializeObject(graphResponseBody);
Enterprise Application permissions on Azure
APP Registration Portal permissions
Can someone guide to any kind of mistake I'm making?
With the authorization token and the permissions applied, I can't see why would I get an AccessDenied response.
It's been more than 48 hours since I applied the permissions, so it's not a sync problem.
Update: So thanks to #juunas I managed to reapply the permissions and the token now shows all the permissions applied on the Application Portal (User.Read.All, Directory.Read.All and Group.Read.All), but the API still returns 403 status code (Authorization_RequestDenied).
I've tried another endpoint without the /me just to make sure that is not a reference problem, but it also returns 403 status code.
One thing that is funny is that the App was registered on the new app portal as I said, and it appears on Enterprise Applications on Azure, but not on my App Registrations, so I can only alter permissions on the new App Portal. It should be like this, since I'm using a new registration portal?
After a discussion in the comments, the problem was fixed by re-consenting the permissions similarly as shown in my blog post: https://joonasw.net/view/the-grant-requires-admin-permission (though it is written for v1).
To run admin consent again, you need to add prompt=admin_consent to the authorize URL.
Okay, so a few minutes after the update on the original post, the token was accepted by the endpoints.
The only problem is that the graph API does not recognize the ID of the user logged in to use the /me endpoints, but I bypassed that using the /{group-id}/members endpoint (in my case, it's not how I wanted but solves my problem).
Thanks #juunas for the help!

Not able to extract access token google service account

I have a consumer google account of the form
"me#gmail.com" for which I have a service account of the form
"Something#developer.gserviceaccount.com". I am trying to use the private key generated for this service account to generate an access token and then may be edit or view the calendar associated with "me#gmail.com".
The authentication code:
String emailAddress = "something#developer.gserviceaccount.com";
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
File file = new File("path to .p12 file");
HttpTransport httpTransport = GoogleNetHttpTransport
.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAddress)
.setServiceAccountPrivateKeyFromP12File(file)
.setServiceAccountScopes(
Collections.singleton("https://www.googleapis.com/auth/calendar"))
.setServiceAccountUser("me#gmail.com")
.build();
String accessToken = credential.getAccessToken();
But the access token generated is null. The service account has edit permissions. The program is able to access the .p12 file.
Any cue as to where am I going wrong?
I think you've misunderstood how Service Accounts work. Impersonating a user only works within a Google Apps domain. You can't use a Service Account to impersonate a gmail account.
I doubt you get an access token when using a service account. If you were using OAuth2 dance and prompting the user for permissions then yes can get an access token, etc.. This is the correct way to initialize the API Calendar instance from a Google Credential object:
import com.google.api.services.calendar.Calendar;
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
You can then use the Calendar instance to make API calls. More information can be found here:
https://developers.google.com/admin-sdk/directory/v1/guides/delegation
https://developers.google.com/google-apps/calendar/quickstart/java

How to make API requests with an access_token for a Service Account

My end goal is to be able to retrieve place details from Google's API.
I need to do this as a Service Account, since this is kicked off as a background task on my server. Service Accounts require you to exchange a JWT (JSON Web Token) for an access_token. I finally got that working and am receiving an access_token. Phew.
Now however, I don't know what to do with this access_token.
The Place Details API says that the key parameter is required, but I don't have a key. Just an access_token. Using that value for key or changing the name of the paramater to access_token is not working.
Ultimately I need to be able to hit a URL like so:
https://maps.googleapis.com/maps/api/place/details/json?reference={MY_REFERENCE}&sensor=false&key={MY_ACCESS_TOKEN}
How do I use my Access Token to make a request to the Google Place Detail APIs?
Update 1
Still no success, but I thought I'd post the details of my request in case there's something wrong with what I'm submitting to Google.
I'm using the JWT Ruby library, and here are the values of my claim set:
{
:iss => "54821520045-c8k5dhrjmiotbi9ni0salgf0f4iq5669#developer.gserviceaccount.com",
:scope => "https://www.googleapis.com/auth/places",
:aud => "https://accounts.google.com/o/oauth2/token",
:exp => (Time.now + 3600),
:iat => Time.now.to_i
}
Looks sane to me.
Create the service account and its credentials
You need to create a service account and its credentials. During this procedure you need to gather three items that will be used later for the Google Apps domain-wide delegation of authority and in your code to authorize with your service account. These three items are your service account:
• Client ID.
• Private key file.
• Email address.
In order to do this, you first need a working Google APIs Console project with the Google Calendar API enabled. Follow these steps:
Go to the Google APIs Console.
Open your existing project or create a new project.
Go to the Service section.
Enable the Calendar API (and potentially other APIs you need access to).
You can now create the service account and its credentials. Follow these steps:
Go to the API Access section.
Create a client ID by clicking Create an OAuth 2.0 client ID...
Enter a product name, specify an optional logo and click Next.
Select Service account when asked for your Application type and click Create client ID.
At this point you will be presented with a dialog allowing you to download the Private Key as a file (see image below). Make sure to download and keep that file securely, as there will be no way to download it again from the APIs Console.
After downloading the file and closing the dialog, you will be able to get the service account's email address and client ID.
You should now have gathered your service account's Private Key file, Client ID and email address. You are ready to delegate domain-wide authority to your service account.
Delegate domain-wide authority to your service account
The service account that you created now needs to be granted access to the Google Apps domain’s user data that you want to access. The following tasks have to be performed by an administrator of the Google Apps domain:
Go to your Google Apps domain’s control panel. The URL should look like: www.google.com/a/cpanel/mydomain.com
Go to Advanced tools... > Manage third party OAuth Client access.
In the Client name field enter the service account's Client ID.
In the One or More API Scopes field enter the list of scopes that your application should be granted access to (see image below). For example if you need domain-wide access to the Google Calendar API enter: www.googleapis.com/auth/calendar.readonly
Click the Authorize button.
Your service account now has domain-wide access to the Google Calendar API for all the users of your domain, and potentially the other APIs you’ve listed in the example above.
Below is a description that uses a service account to access calendar data in PHP
The general process for service account access to user calendars is a follows:
• Create the Google client
• Set the client application name
• If you already have an Access token then check to see if it is expired
• If the Access token is expired then set the JWT assertion credentials and get a new token
• Set the client id
• Create a new calendar service object based on the Google client
• Retrieve the calendar events
Note: You must save the Access token and only refresh it when it is about to expire otherwise you will receive an error that you have exceeded the limit for the number of access tokens in a time period for a user.
Explanation of Google PHP Client library functions used:
The client object has access to many parameters and methods all of the following are accessed through the client object:
Create a new client object:
$client = new Google_Client();
Set the client application name:
$client->setApplicationName(“My Calendar App”);
Set the client access token if you already have one saved:
$client->setAccessToken($myAccessToken);
Check to see if the Access token has expired, there is a 30 second buffer, so this will return true if the token is set to expire in 30 seconds or less. The lifetime of an Access token is one hour. The Access token is actually a JSON object which contains the time of creation, it’s lifetime in seconds, and the token itself. Therefore no call is made to Google as the token has all of the information locally to determine when it will expire.
$client->isAccessTokenExpired();
If the token has expired or you have never retrieved a token then you will need to set the assertion credentials in order to get an Access token:
$client->setAssertionCredentials(new Google_AssertionCredentials(SERVICE_ACCOUNT_NAME,array(CALENDAR_SCOPE), $key,'notasecret','http://oauth.net/grant_type/jwt/1.0/bearer',$email_add));
Where:
SERVICE_ACCOUNT_NAME is the the service account email address setup earlier.
For example:’abcd1234567890#developer.gserviceaccount.com’
CALENDAR_SCOPE is the scope setup in the Google admin interface.
For example: ‘https://www.googleapis.com/auth/calendar.readonly’
$key is the content of the key file downloaded when you created the project in Google apps console.
$email_add is the Google email address of the user for whom you want to retrieve calendar data.
Set the client id:
$client-setClientId(SERVICE_CLIENT_ID);
Where:
SERVICE_CLIENT_ID is the service account client ID setup earlier.
For example: ‘abcd123456780.apps.googleusercontent.com’
Create a new calendar service object:
$cal = new Google_CalendarService($client);
Several options can be set for calendar retrieval I set a few of them in the code below, they are defined in the api document.
$optEvents = array('timeMax' => $TimeMax, 'timeMin' => $TimeMin, 'orderBy' => 'startTime', 'singleEvents' => 'True');
Get the list of calendar events and pass the above options to the call:
$calEvents = $cal->events->listEvents('primary', $optEvents);
Loop through the returned event list, the list is paged so we need to fetch pages until the list is exhausted:
foreach ($calEvents->getItems() as $event) {
// get event data
$Summary = $event->getSummary();
$description = $event->getDescription();
$pageToken = $calEvents->getNextPageToken();
if ($pageToken) { // if we got a token the fetch the next page of events.
$optParams = array('pageToken' => $pageToken);
$calEvents = $cal->events->listEvents('primary', $optParams);
} else {
break;
}
}
Get the Access token:
$myAccessToken=$client->getAccessToken();
Save the access token to your permanent store for the next time.
The language isn't important php, ruby, .net, java the process is the same. The api's console shows the Places API as supporting service accounts so it should be possible to access it.
As far as using the token please have a look at https://code.google.com/p/google-api-ruby-client/ code as the usage is clearly defined in the code repository. Doesn't make any difference if the access token is for a service account or a single user the process for using the token is the same. See the section titled "Calling a Google API" in the following link: https://developers.google.com/accounts/docs/OAuth2InstalledApp
The access token is sent in the http authorization header along with the request.For a calendar request it would look something like the following:
GET /calendar/v3/calendars/primary HTTP/1.1
Host: www.googleapis.com
Content-length: 0
Authorization: OAuth ya29.AHES6ZTY56eJ0LLHz3U7wc-AgoKz0CXg6OSU7wQA

Resources