Microsoft Teams / Graph API: All about Scopes

So we have our Microsoft Teams app set up, and can successfully authenticate to get a user’s information. But we’ll probably want to more with Teams. To do that, we’ll need to ask for more permissions from the user, which we’ll do during auth with “scopes”. Depending on what we want to do, we’ll need to ask specific scopes that covers that functionality. One note, we’re mostly focusing on Work accounts… Personal accounts are fairly limited in what they allow for Personal/Free Teams tenants.

Delegated vs Application scopes

The Microsoft docs have a full list of scopes that you’ll probably want to bookmark if you do anything with the Graph API. The first thing you may notice is that there are “delegated permissions” and “application permissions”.

There’s a page that goes into detail about everything, but basically, Application permissions are set on your app’s page in the Azure portal. They’ll be that same for everyone, you set the “scope” parameter to https://graph.microsoft.com/.default , and they’ll all require a Teams admin to consent for users to use them. I’ll go into admin consent in a moment.

Delegated permission are added to “scope” parameter and can either require admin consent or not. The delegated permission allow for more flexibility, so that’s what we’ll be using. Also, there are a few Graph API endpoints that don’t require an admin to consent to them, so it opens up more possibilities.

To Admin Consent or Not to Admin Consent

There are quite a few API endpoints that only provide basic information about various parts of Teams, and don’t require a Teams admin to consent to them. Though, there are still cases where an admin locks down their tenant so much that even non-admin consent endpoints may not work.

For example, if we want to get a list of Teams that a user is a member of, during auth, we’ll need to request one of these scopes: Team.ReadBasic.All, TeamSettings.Read.All, TeamSettings.ReadWrite.All, User.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All. In the documentation, they list the scopes needed in order of least privileged to most privileged, meaning how much data your app will have access to. It’s best practice to use the lowest privilege that your app needs, but once you know what endpoints your app needs to hit, you may be able to use an elevated one to cover multiple endpoints.

In the “list of Teams” example, we can ask for the “Team.ReadBasic.All” scope, which does not require an admin to approve its usage. However, if we notice we also need to be able to update a user’s info, we’ll need to request “User.ReadWrite.All” which does require an admin to consent… and we could just use that single scope to cover both endpoints.

If we decide to use the “application permissions” instead of delegated ones, they ALL require an admin to consent. This likely means a non-admin user would try to login, then get stopped on Microsoft’s scopes page without being able to continue. So let’s stick with non-admin, delegated permissions to see what we can do…

Getting a channel list

For this task, we want to get all the channels a user is a member of. Luckily, we can get that data without (generally) needing an admin to approve it. Let’s update our login method:

Route::get('login', function () {
    $authUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
    $query   = http_build_query([
        'client_id'     => config('services.microsoft.client_id'),
        'client_secret' => config('services.microsoft.client_secret'),
        'response_type' => 'code',
        'redirect_uri'  => secure_url('/login-redirect'),
        'scope'         => 'User.Read Team.ReadBasic.All Channel.ReadBasic.All offline_access'
    ]);

    return redirect()->away($authUrl . '?' . $query);
})->name('login');

We added two new scopes, and those permission should now show up on the Microsoft login page

Now, after they get redirected, we can make the endpoint calls we want. First, to get the list of the Teams the user is in, grab the first Team from the list, then get the channels in that Team.

Route::get('login-redirect', function (\Illuminate\Http\Request $request) {
    $authReponse = \Illuminate\Support\Facades\Http::asForm()->post('https://login.microsoftonline.com/common/oauth2/v2.0/token', [
        'client_id'     => config('services.microsoft.client_id'),
        'client_secret' => config('services.microsoft.client_secret'),
        'code'          => $request->input('code'),
        'grant_type'    => 'authorization_code',
        'redirect_uri'  => secure_url('/login-redirect')
    ]);

    $accessToken = $authReponse['access_token'];

    $myFirstTeam     = \Illuminate\Support\Facades\Http::withToken($accessToken)->get('https://graph.microsoft.com/v1.0/me/joinedTeams')['value'][0];
    return [
        'id'          => $myFirstTeam['id'],
        'name'        => $myFirstTeam['displayName'],
        'description' => $myFirstTeam['description'],
        'channels'    => \Illuminate\Support\Facades\Http::withToken($accessToken)->get('https://graph.microsoft.com/v1.0/teams/' . $myFirstTeam['id'] . '/channels')['value']
    ];
})->name('login.redirect');

Now, after logging in, authenticating, and being redirected back to our site… we should get something like this:

{
  "id": "aaaaaaaa-bbbb-cccc-1111-123456789012",
  "name": "Matula Teams",
  "description": "Main Team for the Matula Tenant",
  "channels": [
    {
      "id": "19:aaaaaaaaaaaa@thread.skype",
      "displayName": "General",
      "description": "Check here for organization announcements and important info.",
      "email": "",
      "webUrl": "https:\/\/teams.microsoft.com\/l\/channel\/19%3...",
      "membershipType": "standard"
    },
    {
      "id": "19:bbbbbb@thread.skype",
      "displayName": "Teams Teamy Teamteam",
      "description": "So many Teams",
      "email": "",
      "webUrl": "https:\/\/teams.microsoft.com\/l\/channel\/19%...",
      "membershipType": "standard"
    },
    {
      "id": "19:ccccccc@thread.skype",
      "displayName": "Secret Teams. Shhhh",
      "description": null,
      "email": null,
      "webUrl": null,
      "membershipType": "private"
    }
  ]
}

Now, with just adding a few scopes, we’re able to get some good information about the user’s Teams and the channels they’re in. In the next post, we’ll see about a practical application for all this.

Microsoft Teams / Graph API: oAuth and PHP

In the previous post, we created a Microsoft Teams app and bot so we can use the Graph API. We should now have a “client id” and a “client secret” that is needed to make authentication requests, and get a user’s access token.

Install Laravel

To make things simple, we’ll be building the authentication code using the Laravel v8 PHP framework. Also please note, I’m more focused about functionality, so I won’t worry about code design and architecture. All the code will live in the routes/web.php file as part of a closure. In a production environment, we’d want to split that code out to Controllers and make sure our components are placed in logical places where we can reuse code.

There are plenty of good, existing oAuth clients for PHP, like the one from the PHP League, but we’ll be rolling our own. If you need to integrate with multiple services, I would highly recommend using one of those packages. Since all we’re doing is Microsoft, we’ll be using the HTTP client that comes with Laravel, and creating the system directly.

Auth button

Let’s start with a button that the user will click and then be directed to login with Microsoft. Open up the /resources/views/welcome.blade.php file and replace the <body> with a simple button.

<body>
    <div style="width:300px;margin:20px auto;">
        <a href="/login">
            <button style="border:1px solid #999;padding:10px">Login with Microsoft</button>
        </a>
    </div>
</body>

Now, when they click the button and go to our /login route, we need to redirect them to the Microsoft login page. So open the routes/web.php file and add the new route.

Route::get('login', function() {
   $authUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
   return redirect()->away($authUrl);
});

Now if we try to login, we’ll get an error page on Microsoft

We need to update the login code to add the needed parameters to our redirect url. First off, we should save our client id and secret somewhere. In the root directory of Laravel should be a .env file, where we can store our environment variables

MICROSOFT_CLIENT_ID=11111111-2222-3333-aaaa-bbbbbbbbbbbb
MICROSOFT_CLIENT_SECRET=tOtallYfAkeSecRet

Then open up /config/services.php and add a new third party configuration

'microsoft' => [
        'client_id'     => env('MICROSOFT_CLIENT_ID'),
        'client_secret' => env('MICROSOFT_CLIENT_SECRET')
  ]

Now we can update our login code to add in the needed parameters.

Route::get('login', function () {
    $authUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
    $query   = http_build_query([
        'client_id'     => config('services.microsoft.client_id'),
        'client_secret' => config('services.microsoft.client_secret'),
        'response_type' => 'code',
        'redirect_uri'  => secure_url('/login-redirect'),
        'scope'         => 'User.Read offline_access'
    ]);

    return redirect()->away($authUrl . '?' . $query);
})->name('login');

These are the minimum parameters we need to auth with Microsoft and get a user’s access token. There are more possible values depending on our need. The “response_type” of “code” is basically telling Microsoft we want to exchange for an access token, the “redirect_uri” is where the user goes after logging in to Microsoft, and “scope” are the permissions that the user is allowing our app to have. I have a separate post planned that will go into details about scopes, but for now, we’re just getting basic user information.

Now, if we hit our button, we’ll probably see this page:

To setup a correct redirect uri, we’ll need to venture into the AZURE PORTAL!

Updating the app in the Azure Portal

The Azure portal has a LOT in it. Seriously. Maybe that’s the curse of cloud-based admin portals, because AWS dashboard has a similar issue. But I’ll try to break it down easy enough, so we can get our app working.

Step 1, go to All Services and click “Azure Active Directory”:

Step 2, click “App registrations” in the left menu, and if you’re logged in with the same account that created the app in App Studio, you should see that app listed:

Step 3, click the app and then click the “Add a Redirect URI” link:

Step 4, click “Add a platform”. A pop-out window on the right should show up with various options. Since, we’re logging in through a website that sends the user to Microsoft to login, we’ll select “Web”. The Microsoft docs go into more detail about the other options.

Step 5, finally add the full url you want to redirect the user to after they log in. If you’re developing locally, Microsoft lets you use http://localhost/... but otherwise it must be https. Also, the uri is case sensitive, so make sure what you use in the portal is exactly the same when we send it doing the auth.

Finish Logging In

Now let’s go back and try the login button again. This time, we should be greeted on Microsoft by either a login screen, or maybe a login select list. After logging in, we’ll get a page asking us to approve the scopes/permissions we asked for.

Microsoft has two different “flavors” of user – Personal and Work. The Personal user will usually be someone with a “hotmail/live/outlook.com” email account… and the Work user will login with their company email, though on occasion it will be something like “@mycompany.onmicrosoft.com”. The two account types process things a little differently on Microsoft’s backend. For example, a Personal account permission screen will look like:

A Work account will look like:

Once you click “Accept” you’ll be taken back to the “redirect_uri” we specified in our login route. I’ve set it to secure_url('/login-redirect') which creates an “https” url for our route, though if you’re using localhost, it could be just url('/login-redirect'). We can build that route simply like so:

Route::get('login-redirect', function (\Illuminate\Http\Request $request) {
    return $request->all();
})->name('login.redirect');

Now, if you click “Accept” on the Microsoft site, you get back to our redirect page, and will show a “code” (on Work accounts, they might be a “session_state” value as well). We need to use that code and make another call to a Microsoft api to exchange it for an actual access token. Let’s update that function:

Route::get('login-redirect', function (\Illuminate\Http\Request $request) {
    $authReponse = \Illuminate\Support\Facades\Http::asForm()->post('https://login.microsoftonline.com/common/oauth2/v2.0/token', [
        'client_id'     => config('services.microsoft.client_id'),
        'client_secret' => config('services.microsoft.client_secret'),
        'code'          => $request->input('code'),
        'grant_type'    => 'authorization_code',
        'redirect_uri'  => secure_url('/login-redirect')
    ]);

    return $authReponse;
})->name('login.redirect');

There are a couple of caveats here. It doesn’t seem like the “token” api accepts a json payload, so we have to send it as application/x-www-form-urlencoded, hence the “asForm()” method. Also, for Personal accounts we don’t need the “redirect_uri” but it IS needed for Work accounts. It’s best to just leave it as a default.

Once again, if we go through the login process, we should be redirected back to our page and see the values returned when we asked for an access token:

{
    token_type: "Bearer",
    scope: "User.Read", // "User.Read profile openid email" on Work accounts
    expires_in: 3600,
    ext_expires_in: 3600,
    access_token: "eyJ123abc....",
    refresh_token: "M.R123abc..."
}

The access token for Work accounts is actually a JWT, and could be decoded at this point to get some basic info about the user. For Personal accounts, it looks like just a long random string. Also, the list of “scopes” that are returned differ depending on if it’s a Personal or Work account.

Quick note: I'll cover scopes in another post, but be warned 
that Personal account logins will strip any scopes they don't 
support, and succeed in logging in. Work accounts will return 
an error letting you know the scope wasn't accepted.

In a full app, we’ll want to store the “refresh_token”, so we can get a new access token without asking the user to log in again. We’d also store the access token, possibly in a cache since it expires in an hour.

Now we can use the token directly, and make our first request to the Graph API. With the one scope we requested, it pretty much only allows us access to the “/me” endpoint.

Route::get('login-redirect', function (\Illuminate\Http\Request $request) {
    $authReponse = \Illuminate\Support\Facades\Http::asForm()->post('https://login.microsoftonline.com/common/oauth2/v2.0/token', [
        'client_id'     => config('services.microsoft.client_id'),
        'client_secret' => config('services.microsoft.client_secret'),
        'code'          => $request->input('code'),
        'grant_type'    => 'authorization_code',
        'redirect_uri'  => secure_url('/login-redirect')
    ]);

    $accessToken = $authReponse['access_token'];

    return \Illuminate\Support\Facades\Http::withToken($accessToken)->get('https://graph.microsoft.com/v1.0/me');
})->name('login.redirect');

In this code, we grab the access token from token response. Laravel’s Http class has a handy withToken() method that adds a “Bearer” token to our request header. Then we hit the ‘/v1.0/me’ endpoint… though we could do ‘/beta/me’. Those beta endpoints are stable, and while they suggest not using them in production, it’s never been an issue and they often have more functionality.

If we login once more, we’ll get our information returned from the Graph API:

{
    @odata.context: "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
    displayName: "Firstname Lastname",
    surname: "Lastname",
    givenName: "Firstname",
    id: "978.....",
    userPrincipalName: "...@hotmail.com",
    businessPhones: [ ],
    jobTitle: null,
    mail: null,
    mobilePhone: null,
    officeLocation: null,
    preferredLanguage: null
}

If you use the “/beta/me” endpoint with a Work account, you’ll actually get a LOT more information, like the licenses that are assigned to the user.

So now we:

  • Have our Teams app and bot
  • Can request an access token
  • Can get information from the Graph API

In the next post, I’ll go into more detail about the scopes and various things we can do in Teams.

Microsoft Teams / Graph API: Create a Teams app

In my role at Mio, I’ve had the opportunity to work fairly extensively with Microsoft Teams and the Microsoft Graph API. One thing I noticed is that their documentation is extensive, but can be overwhelming if you just need to do something simple. My goal is to write a few posts that simplifies the ways to integrate with Teams and use the Graph API.

Creating the app

The first step we need to take is creating an app for us to use. The easiest way to do that is through the Microsoft App Studio app.

After adding that, go into the App Studio, make sure you’re in the “Manifest editor” tab, and choose “Create a new app”. After that, you’ll be greeted with a lot of options you’ll need to make your app.

The App details are fairly self-explanatory, and you only need to worry about the ones with the star. For “App ID”, I just click the “Generate” button and it fills in a UUID for us. “Package Name” is basically like a web url, but in reverse, so mine is something like “com.terrymatula.yadayada”… “Version” should be 1.0.0 to start and should align with semantic versioning.

The various website URLs can be anything while we test. The “Branding” will need to have 2 icons, one that’s 192px by 192px, and another that’s 32×32. After that page is filled out, we should go to the Capabilities step. We can add a Tab, Bot, Connector, or Message Extension. For our purposes, we only need to worry about the Bot.

Go to the Bots step and click the Set up button. This will allows us to either connect an existing Microsoft bot we’ve already created, or create a brand new one. We’ll do a new one.

We don’t need to deal with the “Messaging bot” or “Calling bot” options at the moment. We have 3 options for “Scope”, which is basically where we want the bot to be able to work. For just one-on-one chats with the user, we choose “Personal”… for chats that include multiple users, we choose “Group Chat”… if we want to use the app in a regular Teams channel, choose “Team”. At the very least for our purposes, we’ll need to select “Team”.

After creating the bot, the screen will show the new bot with a UUID underneath. We need to save this value as our “Client ID”. Then click “Generate new password”, and it will popup a window with a password, which we need to save (it won’t be shown again) as our “Client Secret”

That’s really all we need for now. With the Client ID and Client Secret, we can then go through the oAuth process to get a Teams user’s access token and make Graph API requests, which I’ll cover in the next post.