Microsft Graph API Access Token - c#

When I use the graph explorer (https://developer.microsoft.com/en-us/graph/graph-explorer) to call graph API (like teams api), it automatically provides me with an access token which has the permissions and authentication to do tasks (such as creating a team and adding people).
However, when I try to search for a way to get a access token (https://learn.microsoft.com/en-us/graph/auth-v2-user), it seems to be the case that I would have to register an app with Azure AD (which to begin with only has Read permissions and would not allow me to create teams for example), and follow more steps to get an access token.
My questions is, why is this the case that the access token that is provided through graph explorer lets me do everything while I have to go through so many more steps to get a token by myself (such as creating an app, requesting permissions, and then getting the token). Or is there a simpler way to get access to the access token (with me as the user) that I am not aware of to use graph API?

That's because Graph Explorer is also registered as an application and exists as a service principal/enterprise application in your Azure AD tenant.
Every single application that gets tokens from Azure AD must be registered as an app somewhere.
In case of multi-tenant applications like Graph Explorer, it is registered in one tenant and a local representation of the app (a service principal) is created when the first user consents to permissions required by the app. (or it exists by default, some Microsoft apps exist in every tenant at creation time)

Related

Azure DevOps API access without a user

Is it possible to pull work items from the DevOps API without needing a user to be logged in to get an access token every time?
I am trying to create a back-end service that pulls work items from the API every so often to generate a report. Can I just generate a one-time access key to use with that back-end service?
I've looked around the documentation, but it seemed like it all requires either a PAT or Azure Active Directory authorization/authentication.
Here's the docs for the API: Link
you can do something like this https://learn.microsoft.com/en-us/azure/devops/organizations/settings/manage-authorizations?toc=%2Fazure%2Fdevops%2Forganizations%2Ftoc.json&bc=%2Fazure%2Fdevops%2Forganizations%2Fbreadcrumb%2Ftoc.json&view=azure-devops
and
https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops
Basically authorize applications to use devops based on your credentials using oauth. similar to an app registration.
Thats the only way I can see without PAT and manual login each time.
Instead of your personal account, you could create a fake AAD user then add it to your Azure DevOps Service.
Use that account to create a Personal Access Token. Similar to Build Service account to pull source code/work items. This should be a easy way to track everything.
But the limitation here is also obvious: this needs involvement of IT department, and also causes additional costs, since every user is billed.
Allow personal access tokens that do not expire is not supported right now. There is a related user voice.
As an alternatively way you could use OAuth just as alphaz18 suggested. Details please refer-- Authorize access to REST APIs with OAuth 2.0

Google Calendar API. Adding an event to someone calendar throws error "Error 401: invalid_client" just when authenticating

I have a C# class library from which I am trying to add an event to someone calendar just by using his/her email address and password as credentials. So I debug it and once started a new page in the internet browser is open and below error is displayed:
Below the code:
// It crashes when calling GoogleWebAuthorizationBroker.AuthorizeAsync
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "myGoogleAccount#gmail.com",
ClientSecret = "myGoogleAccountPasswordHere",
},
new[] { CalendarService.Scope.Calendar },
System.Environment.UserName,
CancellationToken.None).Result;
// Create the service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
Why this error is happening? ClientId is not the gmail account?
Also why a new page in internet browser is opened? I want to do authentication without opening a page in the internet browser because this class library is called from a windows service so I need authentication to be done in the background.
Answer:
In order to insert methods into a user's Calendar, you need the user to give your application permission to make actions on their behalf. This is done using a Google Cloud Platform (GCP) Project, with OAuth2 Authentication.
More Information:
Each application which runs and takes actions on behalf of a Google account user has to have the scope of its ability well defined so that it can't start doing things that a user hasn't given it permission to do.
For example: if you give an application permission to create Calendar events, you don't want it to be able to do other things such as read your emails or download the contents of your Drive.
In order to designate what your application has the power to do, it needs to be registered with Google. As you have already deduced in your question and comments, the Client ID and Client Secret required by an application connecting to a G Suite API isn't simply the username and password of a Google Account, but a designated ID-secret ID pair which is provided by Google to identify your application.
OAuth2:
OAuth2 is a specific authorisation framework. The framework is defined in RFC 6749 and sets out the process in which a user can authorise an application to access their account. The limit of the authorisation is defined by the scope of the application on authorisation, and can not be changed without explicit re-authorisation by the user.
Before continuing it's worth defining a few important terms here:
User:
A user is the person; the individual that has an account and gives permission for an application to take actions on their behalf.
Client or Application:
A Client or Application is a program which is designed to take actions over HTTP by connecting to a service's API. Applications can be mobile apps, web apps or desktop clients.
Authorisation Server:
An Authorisation server is a server which is separate from the servers that store user resources. It verfies the user's identity and provides a grant which can be used to get an access token to a resource server.
Resource Server:
This is the server where user data is stored. This could be anything from user information to files or emails.
The authorisation flow has already been well documented, but for the sake of this scenario we can abstract it down to the following steps:
An Application wishes to take an action on a resource server on behalf of a user.
The Application makes an authorisation request to the user. This is generally presented as a login page for the account for which the application is accessing.
The user logs in to their account and is presented with an OAuth consent screen - this contains information such as the application's name, and the list of tasks that it is requesting authorisation for. These are often generic, and will say something like See and download all your Google Drive files or View and edit events on all your calendars. This allows the user to know what they are authorising before they confirm.
An Authorisation Grant is given to the application.
The Application provides the obtained authorisation grant along with its assigned client credentials to an authorisation server.
On verifying that both the user's grant and the client's credentials are correct, the authorisation server returns an access token which can be used to access the requested and approved resources. Note: This is normally all handled by your client library for whichever language you use.
The Application can now make a request to the resource server, providing the access token obtained from the authorisation flow. It is at this point that the permitted resources can be accessed.
Google Cloud Platform Projects:
A GCP project what Google sees as your application. The registration for your application is required to be able to obtain the client ID and client secret which your application will need in order to get an access token in the authorisation flow.
In the GCP console you can set up all the required services that your application needs. Each API you wish to use has to be enabled for your application, as there are many Google services with APIs and they are disabled by default.
Once a GCP Project has been created, you can use the API Library (From the ≡ > APIs & Services > Library menu item on the left) to find and enable the API. Note that for your use case you will want to enable the Google Calendar API and not the CalDAV API.
You will also need to set up a consent screen before obtaining credentials for your application. An OAuth consent screen is what your users will be presented with in the first step of the OAuth flow:
When setting up your OAuth consent screen, you will need to provide the following information:
Application type (public or internal to your domain)
Application name
The scopes that your application needs (explained in the next section)
After the consent screen has been set up, you can download the client credentials for your application. With these, your application has permission to run as a client, but each user that has their resources accessed will still have to give their explicit permission to allow the application to do so.
Scopes:
Within a single API there can be many scopes of access - having read-only access to calendar events is vastly different to having complete read-write access to all calendars that a user owns. This is where scopes come into play.
A scope is defined as its namesake; that is to say, a scope defines the scope of access an application has to a service. Even though an entire API has been enabled for a project doesn't mean that you need to use all features of the API. For this reason, scopes need to be defined.
Scopes are defined in the application itself before making the initial request for the user grant. In C#, for example (taken from the .NET Calendar API Quickstart):
// scopes are defined as an array of strings:
static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
...
UserCredential credential;
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
The access token that is stored is based on the scopes that were defined in the call. If a method is called which needs a different scope to those which the token grants access to, the call will fail with a 403: Unauthorized error. The required scope will need to be added to the application, the old access token deleted and the user will need to grant permission for the new scopes.
Service Accounts:
As well as regular users, there is another special type of Google account called a Service Account. From the documentation:
A service account is a special kind of account used by an application or a virtual machine (VM) instance, not a person. Applications use service accounts to make authorized API calls.
Normally, every user for whom you wish to perform tasks or access resources needs to give explicit permission for your application to do so. For G Suite domains, however, you can use a service account with domain-wide delegation to complete tasks on behalf of users without the requirement.
Service accounts use a special kind of service-account credential which can be created in GCP and used in your application. Rather than making a UserCredential object, a ServiceAccountCredential is needed which doesn't require involvment by an end user.
When running a service account on behalf of a user with domain-wide delegation, the name of the user needs to be specified in the delegated credentials so the application knows which user in the domain to run as. If a user is not provided, the service account will run the code as itself; which is useful in some cases but often times will not return an error and so it may not be clear for whom the operation was run.
Note: While Service Accounts can be created by anyone, domain-wide delegation of authority can only be accomplished for a G Suite domain, and not #gmail.com addresses. All Gmail account users must give explicit permission for an application to run on thier behalf as set out by the OAuth flow.
References:
Using OAuth2 to Access Google APIs | Google Identity Platform
RFC 6749 - The OAuth2 Authorization Framework
OAuth - Wikipedia | #OAuth2
Google Cloud Platform Console
Google APIs Explorer | Google Developers
.NET Quickstart | Calendar API | Google Developers
Service Accounts | Cloud IAM Documentation | Google Cloud
Perform G Suite Domain-Wide Delegation of Authority | Directory API
OAuth 2.0 | API Client Library for .NET
Related Questions:
Google API Service Account. Can only see service accounts drive even with Domain Wide Delegation Access
Creating events using the Google Calendar API and Service Account

App Registrations: Deletion of permissions is not reflected in API call

I have access to my Azure AD Portal. I also have an external ASP.NET application which is accessing the Microsoft Graph API. For this purpose I add an App Registration which give me an Application ID and Key to be able to configure my ASP.NET application to authenticate itself against the Graph API.
I need the my ASP.NET application to read groups out of Azure AD. I can authenticate successfully but I get an error saying that I have not enough privileges. Then I go back to the Azure Ad Portal and add permissions to the App Registration I added. This works ok so in the end I have the Graph API response on my ASP.NET application.
Now it comes the issue. I selected too many permissions so I want to use the smallest set of permissions that are necessary for my ASP. So I go the Azure Portal AD again and remove some of the permissions. When I test my app again, I still receive the groups even if I have no permissions selected.
I think this is an issue. Or there's some kind of delay? I don't think so because when the API is working and has the proper permissions I can add a group in Azure AD Portal and instantly see it in my ASP.NET application.
This issue is specially annoying because you can't really test the permissions your app needs.
Thanks.

Registering Application / Obtaining Tenant information from Azure programmatically (C# .NET Core)

Does Azure support a programmatic way of registering an application via the users Microsoft account (Using Azure Active Directory)?
Example 1
I am unable to find anything through the Microsoft docs. Everything related to this indicate a manual application registration has to be done, then manually entered. However, I want my application to support multiple tenants without having to manually input all the information into environment variables.
I would like my application to register itself after a user has signed into their Microsoft account and allow access to my application (similar to Github integration). With that registration, it can then pull down the users tenant information and generate a key for itself.
Edit: I have found some other answers on StackOverflow that mentions using GraphAPI after obtaining a bearer token from Microsoft
Is this still the best way of doing this?

Get shared calendar from different user(meeting room)

// How to get different user / meeting room calendar events?
We are trying with the graph REST API to get calendar events of another user (shared calendar to the authenticated user) or a meeting room (should be an Active Directory user with shared calendar to all users within the organization).
We still get "Forbidden" response.
We can successfully get the user(himself) authenticated calendar events.
We can also get user details of the authenticated user and even of another user (user authenticated as John.Doe#company.com and can get user details of elise#doe.company.com) but we cannot get details of the meeting room user even though it should be a normal user in our AD.
We tried to setup all delegated and even app permission scopes, nothing helped.
Example:
var endpoint = "https://graph.microsoft.com/v1.0/users/"+userId+"/calendarView";
Is there a way to retrieve this information?
The problem is that your token does not have the correct scope. To be able to access shared calendars, you need the Calendars.Read.Shared (or Calendars.ReadWrite.Shared). How you get that scope into your token depends on where you registered the app (which answers your first question!)
Does it matter where or how the application was registered?
Yes, this matters. Both methods will work, but where you register affects how you request authorization and tokens. Also, apps registered in Azure Management Portal can only authenticate Office 365 users, not Outlook.com users. More on this in #2.
Does it matter what authentication URL we use?
Yes! The URL you use is directly related to which place you registered your app. I'm going to break this down below.
App scope permissions vs delegated scope permissions - does it matter which ones we set up in the application? Will our desired functionality work with delegated permissions?
Yes it matters. App permissions are granted to the app, and for Outlook APIs, these are global to the entire organization. So if you grant an app Mail.Read, it can read mail for all users in the org. The app acts as itself, and does not authenticate a user. Because of this, the auth method requires a certificate instead of a client secret. This method is meant for daemon-type apps. You most likely want delegate permissions since you want to authenticate users and then give them access to just those other mailboxes/calendars they are allowed to view.
Do AD permissions somehow influence the permissions user has in the application?
Well yes, in the sense that if you include a .Shared scope in your permissions, what the user has access to is set by what other users have shared with them (and this ties back to AD).
How do I add a shared scope
As I said above, this matters on how you registered your app.
Azure Management Portal
Apps registered in the Azure Management Portal use the "v1" version of Azure's OAuth2 implementation. Under this model, you have to specify the permissions for your app "up front" on the app registration itself. To add a shared permission, you have to modify the app registration in the portal. The permissions are shown in the portal as "Read user and shared calendars" (for Calendars.Read.Shared) and "Read and write user and shared calendars" (for Calendars.ReadWrite.Shared).
If your app is registered here, then you MUST use the v1 auth and token endpoints:
https://login.microsoftonline.com/common/oauth2/authorize
https://login.microsoftonline.com/common/oauth2/token
Additionally, under the v1 scheme, if you add new scopes to your app registration, you MUST have the user's reconsent. Otherwise, the next time they sign in to your app, they will just get the same permissions they had before. To do this, when sending the users to the authorize endpoint, add a prompt=consent parameter to the authorize URL.
Application Registration Portal
Apps registered here use the v2 Azure implementation and gain a few benefits. First, you can authenticate Microsoft accounts (Outlook.com) as well as Office 365 users. Second, adding scopes doesn't require modifying your app registration. And last, you don't have to manually reconsent users, the auth endpoint will detect the change and prompt for you.
Apps registered here use the v2 auth and token endpoints:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize
https://login.microsoftonline.com/common/oauth2/v2.0/token
Scopes are specified in the scope URL parameter in the auth endpoint. So to add the shared scopes, you would just replace your existing Calendars.Read and/or Calendars.ReadWrite with the .Shared equivalent.

Categories

Resources