How to: Get a Microsoft Graph Access Token when logging into Azure Active Directory with Azure App Service
Posted
Thursday, January 12, 2017 9:23 AM
by
CoreyRoth
If you have used Azure App Service, you will have loved how easy it is to set up authentication to providers such as Azure Active Directory and Facebook. It lets you get started with a single line of code. You can literally login with a single line of code like the following:
client.login('aad').then(results => { // successful login
}, error => { // login error
});
This will give you an id_token that you can then turn into a access_token by calling the /.auth/me endpoint with a REST call. However, that access_token won’t have access to anything even though you configured App Service to use an App that has requested specific permissions. CGillum from Microsoft pointed me in the right direction with his post to access the Azure AD Graph, but the Microsoft graph required some tweaks.
You start by going to the Azure Resource Explorer. However, this assumes you have already configured your App Service app to use your particular Azure AD Application that you are creating. Find your app service app in the hierarchy and then open /config/authsettings and click Edit. If you haven’t set your clientSecret yet, you can do so now (although I am not 100% sure it’s required). However, the key parameter is to set additionalLoginParams with the following JSON array.
["response_type=code id_token", "resource=https://graph.microsoft.com"]
This tells /.auth/me to give you the proper access_token when you call it. You can also get a refresh token this way at the same time. Once you have made the changes click the PUT button to send the changes back to the service. Your should look something like this.
Now, when you login again and call the /.auth/me endpoint, you’ll get additional data including an access token that works with Microsoft Graph. If you have logged in before with this particular username and app, you will want to sign out and log back in again to make sure the permissions that you specified in your application get granted. You may need to add the query string parameter prompt=consent on the login page to get it to prompt you for the new graph permissions. Otherwise, you’ll get an access token that won’t work with the Microsoft Graph.
As you can see in the screenshot above, the object returned has a lot more information in it than before. There is nothing particular sensitive in this screenshot either since this is just a demo tenant.