Henrik
Henrik

Reputation: 95

Oauth2 flow for native app with back-end web app calling Graph API

I have the following set up:

The idea is that the user should sign in with OpenID/Oauth2 using his/her Office 365 credentials. The webapp will then call the Microsoft Graph API on behalf of the user (offline as well).

To achieve this I'm pretty sure I need to use the grant type: "Authorization code grant". I can find a lot of example of the Oauth2 flow for browser based apps, and for when the native app calls the Graph API directly... but I want my backend to call the Graph API (and hold the access & refresh tokens).

So the question is how to do this properly? Here is my idea at this point.

  1. From the native app: open a browser, call my web server which will trigger a redirect to the Azure /authorize endpoint (example: https://login.microsoftonline.com/[tenant]/oauth2/v2.0/authorize?client_id=[clientid]&response_type=code&scope=offline_access%20user.read%20calendars.readwrite&response_mode=query&state=12345&redirect_uri=my-scheme://oath2-code-reply

  2. This will trigger authentication/authorization and then send the access code back to the app (using a custom scheme redirect: my-scheme://oath2-code-reply).

  3. The app can then call my web app with this access code, where we can exchange the code for refresh & access code, and also create our own session for the user.

Is this the correct way?

Or should the entire flow occur in the browser and as the final step I open the app again with something like myapp-scheme://?sessionid=[our-own-session]?

Upvotes: 1

Views: 985

Answers (1)

Andre Teixeira
Andre Teixeira

Reputation: 783

For your scenario, you should use the on-behalf-of-flow.

A server-side sample that you can use as reference is https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof - a note is that this sample is a .NET sample using a JavaScript SPA as a client - but hopefully it can guide you. You can use this sample for an overview on how to request tokens for your web api.

A note is that your item '1.' suggests that you are using the 'v2' endpoint. The 'v2' endpoint has some limitations, including for the scenario you are trying to accomplish (request access token to a Web API) - please see this document with information on these limitations, therefore my recommendation is to use the v1 endpoint at this moment for your scenarios -- which mean that you can only authenticate corporate accounts (and not MSA). The documents and samples I've indicated above uses the v1 endpoint.

Upvotes: 1

Related Questions