Coder Social home page Coder Social logo

microsoftgraph / msgraph-sample-azurefunction-csharp Goto Github PK

View Code? Open in Web Editor NEW
47.0 7.0 23.0 751 KB

This sample demonstrates how to use the Microsoft Graph .NET SDK to access data in Office 365 from Azure Functions.

License: MIT License

C# 55.20% JavaScript 38.74% HTML 5.98% CSS 0.08%
microsoft-graph csharp azure-functions devxsample

msgraph-sample-azurefunction-csharp's Introduction

page_type description products languages
sample
This sample demonstrates how to use the Microsoft Graph .NET SDK to access data in Office 365 from Azure Functions.
ms-graph
office-exchange-online
azure-functions
csharp

Microsoft Graph sample Azure Function

.NETLicense.

This sample demonstrates how to use the Microsoft Graph .NET SDK to access data in Office 365 from Azure Functions.

NOTE: This sample was originally built from a tutorial published on the Microsoft Graph tutorials page. That tutorial has been removed.

Prerequisites

App registrations

This sample requires three Azure AD application registrations:

  • An app registration for the single-page application so that it can sign in users and get tokens allowing the application to call the Azure Function.
  • An app registration for the Azure Function that allows it to use the on-behalf-of flow to exchange the token sent by the SPA for a token that will allow it to call Microsoft Graph.
  • An app registration for the Azure Function webhook that allows it to use the client credential flow to call Microsoft Graph without a user.

NOTE This example requires three app registrations because it is implementing both the on-behalf-of flow and the client credential flow. If your Azure Function only uses one of these flows, you would only need to create the app registrations that correspond to that flow.

  1. Open a browser and navigate to the Azure Active Directory admin center and login using an Microsoft 365 tenant organization admin.

  2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

Register an app for the single-page application

  1. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to Graph Azure Function Test App.
    • Set Supported account types to Accounts in this organizational directory only.
    • Under Redirect URI, change the dropdown to Single-page application (SPA) and set the value to http://localhost:8080.
  2. Select Register. On the Graph Azure Function Test App page, copy the values of the Application (client) ID and Directory (tenant) ID and save them, you will need them in the later steps.

Register an app for the Azure Function

  1. Return to App Registrations, and select New registration. On the Register an application page, set the values as follows.

    • Set Name to Graph Azure Function.
    • Set Supported account types to Accounts in this organizational directory only.
    • Leave Redirect URI blank.
  2. Select Register. On the Graph Azure Function page, copy the value of the Application (client) ID and save it, you will need it in the next step.

  3. Select Certificates & secrets under Manage. Select the New client secret button. Enter a value in Description and select one of the options for Expires and select Add.

  4. Copy the client secret value before you leave this page. You will need it in the next step.

    IMPORTANT This client secret is never shown again, so make sure you copy it now.

  5. Select API Permissions under Manage. Choose Add a permission.

  6. Select Microsoft Graph, then Delegated Permissions. Add Mail.Read and select Add permissions.

  7. Select Expose an API under Manage, then choose Add a scope.

  8. Accept the default Application ID URI and choose Save and continue.

  9. Fill in the Add a scope form as follows:

    • Scope name: Mail.Read
    • Who can consent?: Admins and users
    • Admin consent display name: Read all users' inboxes
    • Admin consent description: Allows the app to read all users' inboxes
    • User consent display name: Read your inbox
    • User consent description: Allows the app to read your inbox
    • State: Enabled
  10. Select Add scope.

  11. Copy the new scope, you'll need it in later steps.

  12. Select Manifest under Manage.

  13. Locate knownClientApplications in the manifest, and replace it's current value of [] with ["TEST_APP_ID"], where TEST_APP_ID is the application ID of the Graph Azure Function Test App app registration. Select Save.

NOTE Adding the test application's app ID to the knownClientApplications property in the Azure Function's manifest allows the test application to trigger a combined consent flow. This is necessary for the on-behalf-of flow to work.

Add Azure Function scope to test application registration

  1. Return to the Graph Azure Function Test App registration, and select API Permissions under Manage. Select Add a permission.

  2. Select My APIs, then select Load more. Select Graph Azure Function.

  3. Select the Mail.Read permission, then select Add permissions.

  4. In the Configured permissions, remove the User.Read permission under Microsoft Graph by selecting the ... to the right of the permission and selecting Remove permission. Select Yes, remove to confirm.

Register an app for the Azure Function webhook

  1. Return to App Registrations, and select New registration. On the Register an application page, set the values as follows.

    • Set Name to Graph Azure Function Webhook.
    • Set Supported account types to Accounts in this organizational directory only.
    • Leave Redirect URI blank.
  2. Select Register. On the Graph Azure Function webhook page, copy the value of the Application (client) ID and save it, you will need it in the next step.

  3. Select Certificates & secrets under Manage. Select the New client secret button. Enter a value in Description and select one of the options for Expires and select Add.

  4. Copy the client secret value before you leave this page. You will need it in the next step.

  5. Select API Permissions under Manage. Choose Add a permission.

  6. Select Microsoft Graph, then Application Permissions. Add User.Read.All and Mail.Read, then select Add permissions.

  7. In the Configured permissions, remove the delegated User.Read permission under Microsoft Graph by selecting the ... to the right of the permission and selecting Remove permission. Select Yes, remove to confirm.

  8. Select the Grant admin consent for... button, then select Yes to grant admin consent for the configured application permissions. The Status column in the Configured permissions table changes to Granted for ....

Configure the sample

  1. Run ngrok using the following command. (Only required if using the change notification webhook portion of the sample)

    ngrok http 7071
  2. Rename config.example.js to config.js and replace the following values:

    • YOUR_TEST_APP_CLIENT_ID_HERE - replace with the client ID for Graph Azure Function Test App
    • YOUR_TENANT_ID_HERE - replace with your tenant ID
    • YOUR_AZURE_FUNCTION_CLIENT_ID_HERE - replace with the client ID for Graph Azure Function
  3. Use dotnet user-secrets set in the GraphSampleFunctions directory to set the following values.

    • apiClientId - the client ID for Graph Azure Function
    • apiClientSecret - the client secret for Graph Azure Function
    • ngrokUrl - your ngrok URL (copy from ngrok output)
    • tenantId - your tenant ID
    • webhookClientId - the client ID for Graph Azure Function Webhook
    • webhookClientSecret - the client secret for Graph Azure Function Webhook

NOTE If you restart ngrok, you will need to update the ngrokUrl value in user secrets with the new ngrok URL and restart the Azure Function project.

Run the sample

The following command (run in the GraphSampleFunctions directory) will start the Azure Function project locally on your machine.

func start

To serve the test client, run your favorite command-line HTTP server in the TestClient directory. For example, you can use dotnet-serve.

dotnet serve -h "Cache-Control: no-cache, no-store, must-revalidate" -p 8080

Open your browser to http://localhost:8080 and sign in with a user in your tenant.

Code of conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Disclaimer

THIS CODE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

msgraph-sample-azurefunction-csharp's People

Contributors

baywet avatar daxianji007 avatar dependabot[bot] avatar github-actions[bot] avatar jasonjoh avatar microsoft-github-policy-service[bot] avatar mtrilbybassett avatar philip-young avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

msgraph-sample-azurefunction-csharp's Issues

NullReferenceException in SetSubscription

Where did you get the code?

Describe the bug
I followed steps described in tutorial https://docs.microsoft.com/en-us/graph/tutorials/azure-functions.
When I use frontend app and try to subscribe I receive NullReferenceException
at Microsoft.Graph.HttpProvider.d__18.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__38.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.BaseRequest.d__341.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at GraphTutorial.SetSubscription.d__3.MoveNext() in C:\Work\msgraph-training-azurefunction-csharp\demo\GraphTutorial\SetSubscription.cs:line 101

To Reproduce
Steps to reproduce the behavior:

  1. As in tutorial launch ngrok set secretes
  2. Launch azure functions in visual studio
  3. launch test app from command line as described in tutorial
  4. Open frontend app in browser
  5. go to subscribtions tab and try to subscribe user

Expected behavior
App should allow to subscribe used

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: chrome
  • Version: 89

Dependency versions

  • Authentication library (MSAL, etc.) version: as in repository
  • Graph library (Graph SDK, REST library, etc.) version: as in repository

Additional context
Add any other context about the problem here.

System.Private.CoreLib: Exception while executing function: SetSubscription. Microsoft.Graph.Core: Object reference not set to an instance of an object

Where did you get the code?

Describe the bug
Hi, I'm having problems when making the susbcription with the App Service URL. I don't have any problem when setting NgrokURL when i open an instance of ngrok local 7071 in cmd

To Reproduce
1.-To test i set ngrokUrl value
image
2.-Once i set it, i can create a subscription
image
image
3.-But if i replace the ngrok value for
image
I get this error
image
Also i tried to create the function in graph explorer i got the same error.

Dependency versions

  • Graph library (Graph SDK, REST library, etc.) version 3.8.0

Latest lib version

The notify code doesn't work with the latest version of Graph as GetRootParseNode takes a Stream. Also getting an error:
Microsoft.Kiota.Abstractions: Content type application/json does not have a factory registered to be parsed.

Any ideas?

Durable Functions Isolated Worker Sample?

Would it be possible to also provide a simple example for a Azure Durable Function using the isolated worked, where the actual call to the Graph API is made from an activity.

Help needed to replace secret from user stores to Key vault

Reference
https://docs.microsoft.com/en-us/graph/tutorials/azure-functions?tutorial-step=5

Update code
Configuration is read from the user secret store, which only applies to your development machine. Before you publish to Azure, you'll need to change where you store your configuration, and update the code in Program.cs accordingly.

Can you please help how can we updated this code while publishing it in Azure Function app. Required code for Azure key vault or any other way .

Object reference not set to an instance of an object

Where did you get the code?

Describe the bug
I've tried both following the tutorial, as well as downloading from GitHub and have what I believe is the same error that the other user posted. Currently can pull new messages, but on subscribing an email address I'm left with an "Object reference not set to an instance of an object" error. It fails out on azurefunctions.js:59 and does so every time.

Error on the web page is: Call to SetSubscription returned 500 "Internal Server Error"

Error in the console is:
[2021-05-14T17:28:38.394Z] Executed 'Notify' (Succeeded, Id=6a4ec2e3-f68e-4a4e-aa28-431bcb4f75a5, Duration=4ms)
[2021-05-14T17:28:39.069Z] Executed 'SetSubscription' (Failed, Id=13cfe347-1cde-4e97-80b8-011ab221e9fc, Duration=1801ms)
[2021-05-14T17:28:39.071Z] System.Private.CoreLib: Exception while executing function: SetSubscription. Microsoft.Graph.Core: Object reference not set to an instance of an object.

To Reproduce
Steps to reproduce the behavior:

  1. Go to Subscriptions
  2. Enter an email address
  3. Click Subscribe
  4. See error

Expected behavior
Should subscribe the email.

Screenshots
N/A

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser Chrome, Firefox and Edge (happens in all browsers)
  • Version [e.g. 22]

Dependency versions

  • Authentication library (MSAL, etc.) version:
  • Graph library (Graph SDK, REST library, etc.) version:

Additional context
Function Runtime Version: 3.0.15417.0
.NET SDK 5.0.202 (x64)
Running this from PowerShell using Azure Command Line
Editor: Visual Studio Code

Compatibility with .NET Core 3.1

Could you please let us know if this can be used in .NET Core 3.1, when I tried doing it I have got compatibility issues with libraries used as they are working with .NET 5?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.