Giter VIP home page Giter VIP logo

azure-functions-microsoftgraph-extension's Introduction

Azure Functions bindings to O365

NOTE: This project is no longer maintained and is not recommended for new development. To integrate with the Microsoft Graph from Azure Functions, please instead see this tutorial.

Prototype for some WebJobs extension bindings.

This provides a sample Azure Function extensions for Office.

This provides a few bindings:

  • [Outlook] - sends emails from an O365 account
  • [OneDrive] - reads/writes a Onedrive file
  • [Excel] - reads/writes an Excel table or worksheet.
  • [Token] - this has been extended to allow binding to the MS Graph SDK's Graph Service Client
  • [GraphWebhookSubscription] - creates, deletes, or refreshes a Graph Webhook. See https://github.com/microsoftgraph/aspnet-webhooks-rest-sample for graph webhooks sample.
  • [GraphWebhookTrigger] - the trigger that activates a function when a Graph Webhook is called for its datatype

The bindings found in the Microsoft Graph extension use the same authentication process as those in the Token Extension. You can see how to use these bindings in the samples directory.

For Authentication

Authentication is built using Easy Auth's token store. (see https://cgillum.tech/2016/03/07/app-service-token-store/ ) The app has an AAD app registered that has been configured with access to the Graph API and given appropriate scopes. The bindings can access the client secret (via appsettings) and use that to perform token exchanges.

The bindings can authenticate in 4 different ways:

  • UserFromId - the token is grabbed on behalf of a provided user id
  • UserFromToken - the token is grabbed on behalf of a provided user id token
  • UserFromRequest - the token is grabbed on behalf of the user id token found in the HTTP header X-MS-TOKEN-AAD-ID-TOKEN
  • ClientCredentials - uses the app's credentials to access AAD

Source layout

The samples directory contains examples of how to use the bindings. The code for both the Token and Microsoft Graph extensions can be found in the src directory, and in-memory tests can be found in the tests directory.

Local Development

First create a Functions app using the Functions CLI found https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local. Be sure to use the Version 2.x runtime.

To install the Token extension, run the command func extensions install --package Microsoft.Azure.WebJobs.Extensions.AuthTokens -v <version>.

To install the Microsoft Graph extension, run the command func extensions install --package Microsoft.Azure.WebJobs.Extensions.MicrosoftGraph -v <version>.

The easiest way to utilize most of the features of these features is to configure an Azure Functions app in the Portal, enable Authentication/Authorization, add the extension, and go through the configuration to enable the proper Microsoft Graph permissions.

If you are making code changes to the extensions themselves and wish to test these locally, you can manually copy the .dll files that you build into your bin directory in your local function app's directory.

App Settings to Modify in local.settings.json:

  • WEBSITE_AUTH_CLIENT_ID - Copy from your App Settings in Kudu from your configured app
  • WEBSITE_AUTH_CLIENT_SECRET - Copy from your App Settings in Kudu from your configured app
  • WEBSITE_AUTH_OPENID_ISSUER - (Optional, Required for a ClientCredentials TokenIdentityMode) Copy from your App Settings in Kudu from your configured app (or set to https://sts.windows.net/<tenantID> for Azure Active Directory)
  • BYOB_TokenMap - A valid local directory that you have read/write access to

Current Version

Latest Version: 1.0.0-beta6 Portal Version: 1.0.0-beta5

If you want to get the latest features and bugfixes, you can manually update to the latest version by following the instructions in the update folder. NOTE: If you update to a different version than the version in the portal, you cannot use the Token and Microsoft Graph templates.

License

This project is under the benevolent umbrella of the .NET Foundation and is licensed under the MIT License

Contributing

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.

azure-functions-microsoftgraph-extension's People

Contributors

baywet avatar connormcmahon avatar fabiocav avatar glennamanns avatar mattchenderson avatar microsoft-github-policy-service[bot] avatar microsoftopensource avatar mikestall avatar msftgits avatar panjkov avatar paulbatum 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

Watchers

 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

azure-functions-microsoftgraph-extension's Issues

Issues with graphToken after updating binding extensions from beta1 to beta2

Hi,
In the Function app created in the portal using csx
after updating Microsoft Graph extensions from beta1 to beta2 using Kudu as advised by @mattchenderson, (to solve issue 'app not found in directory microsoft.com') I have following issues:

  1. On existing Functions with Auth Token or Graph resource binding, I receive error "InvalidOperationException: No value was provided for parameter 'graphToken'."
    image
  2. If I try to add new Auth Token binding, I keep being informed that "Extension is not installed" and prompted to install extension
    image

Support for Multi-Tenancy

Since graph binding forces you to set the issuerURL in the AD Application that is assigned to the function, I am unable to find a way to support multitenancy.

Want I want is that any user from any tenant can call the api and be authenticated against their own Azure AD using delegated permissions. I have it working if I make the calls myself to get the token, but it would be nice if the binding could use the same issuer that was used to issue the authenticated user.

Perhaps i'm missing something, if so just tell me :D

Support for Microsoft.Graph.Beta sdk

As the Microsoft Graph SDK team release support for the Beta version of the Graph with the dotnet SDK it'd be nice to have a beta version of this extension as well under preview to match the behavior.
It's probably only a matter of having two project files and/or nuspec files and it'd allow people to use this extension in combination with the beta endpoint without having to craft requests manually.
Today, because the beta sdk is on the same namespace as the v1.0 one, if you use both the beta sdk and this extension, you end up having conflicts for every entity.
https://www.nuget.org/packages/Microsoft.Graph.Beta/

Azure Function V2 Graph token- invalid_grant, Assertion is not within its valid time range

I am working on Azure function V2 Graph token template. I am getting below error if you don't use the system for a while.
2019-03-13T10:08:10.911 [Error] Executed 'Functions.GraphTest' (Failed, Id=ad2e8baf-6af7-4ac1-86f4-50bf8e936373) {"error":"invalid_grant","error_description":"AADSTS500133: Assertion is not within its valid time range.\r\nTrace ID: 225b4107-f46c-411d-ab13-9aead85cf600\r\nCorrelation ID: 59db5657-4510-4010-a2d4-fc07309c45cd\r\nTimestamp: 2019-03-13 10:08:10Z","error_codes":[500133],"timestamp":"2019-03-13 10:08:10Z","trace_id":"225b4107-f46c-411d-ab13-9aead85cf600","correlation_id":"59db5657-4510-4010-a2d4-fc07309c45cd"}

extensions.csproj

<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.AuthTokens" Version="1.0.0-beta6" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.MicrosoftGraph" Version="1.0.0-beta6" />
<PackageReference Include="Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator" Version="1.0.*" />

Please help me to solve this. As we want this to implemented in our most of the solutions

Credentials time out even though cookie still valid

When using the token mode UserFromRequest, a user encountered the below issue.

2018-04-06T13:24:47.145 [Error] System.Private.CoreLib: Exception while executing function: Functions.getCalendar. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'graphToken'. Microsoft.IdentityModel.Clients.ActiveDirectory: AADSTS70002: Error validating credentials. AADSTS50013: Assertion is not within its valid time range. Trace ID: e9c4c023-b531-45a4-a63c-be4f2e621000 Correlation ID: f5886be0-6846-484f-9d4b-b10711a8047c Timestamp: 2018-04-06 13:24:46Z. Microsoft.IdentityModel.Clients.ActiveDirectory: Response status code does not indicate success: 400 (BadRequest). {"error":"invalid_grant","error_description":"AADSTS70002: Error validating credentials. AADSTS50013: Assertion is not within its valid time range.\r\nTrace ID: e9c4c023-b531-45a4-a63c-be4f2e621000\r\nCorrelation ID: f5886be0-6846-484f-9d4b-b10711a8047c\r\nTimestamp: 2018-04-06 13:24:46Z","error_codes":[70002,50013],"timestamp":"2018-04-06 13:24:46Z","trace_id":"e9c4c023-b531-45a4-a63c-be4f2e621000","correlation_id":"f5886be0-6846-484f-9d4b-b10711a8047c"}. 2018-04-06T13:24:47.489 [Error] Executed 'Functions.getCalendar' (Failed, Id=ae18d8ff-2e42-4f0e-a761-bbc9c33bbf9f)

The user could sign into other sites, so their cookie was still valid.

Bindings for authentication are not generated when the Azure Function is deployed using Visual Studio

Hello,
I've created a new Azure Function v2.0 using Visual Studio 2017. Then I've installed, using NuGet, the packages required to interact with the Microsoft Graph:

<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.AuthTokens" Version="1.0.0-beta3" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.MicrosoftGraph" Version="1.0.0-beta3" />

Then I've changed the signature of the function in order to include the Token attribute:

public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req,
[Token(Identity = TokenIdentityMode.UserFromRequest, IdentityProvider = "AAD", Resource = "https://graph.microsoft.com")]string token, TraceWriter log)
{}

However, when I publish the function on my Azure account and I look at the function.json displayed in the dashboard, the authentication bindings are completely missing:

{
  "generatedBy": "Microsoft.NET.Sdk.Functions-1.0.13",
  "configurationSource": "attributes",
  "bindings": [
    {
      "type": "httpTrigger",
      "methods": [
        "get",
        "post"
      ],
      "authLevel": "anonymous",
      "name": "req"
    }
  ],
  "disabled": false,
  "scriptFile": "../bin/FunctionApp2.dll",
  "entryPoint": "FunctionApp2.Function1.Run"
}

As a consequence, the Azure function isn't working and it always return the following exception:

System.Private.CoreLib: Exception while executing function: GraphApiFunction. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'token'. Microsoft.IdentityModel.Clients.ActiveDirectory: Value cannot be null.

Am I doing something wrong or is there any issue with the current NuGet packages?

Thanks!

Token binding contains hard coded path for token storage

Repro:

  • Create a function
  • Add a Token binding (in my case UserFromRequest, https://graph.microsoft.com)
  • Add the proper configuration (WEBSITE_*…)
  • F5 Debug

You'll get the following error message in the functions host console

System.Private.CoreLib: Exception has been thrown by the target of an invocation. System.IO.FileSystem: Could not find a part of the path 'D:\home\data\byob_graphmap'

Fortunately plugging a usb key and affecting the D letter works around the issue, but this is far from ideal.

The graph token has no scopes. Client Credentials

I got this error when playing with the sample

[FunctionName("WebhookSubscribe")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [GraphWebhookSubscription(
                Identity = TokenIdentityMode.ClientCredentials,
                SubscriptionResource = "users/%UserId%/drive/root",
                ChangeTypes = new [] {GraphWebhookChangeType.Created, GraphWebhookChangeType.Updated },
                Action = GraphWebhookSubscriptionAction.Create)] out string clientState,
            ILogger log)
        {
            clientState = Guid.NewGuid().ToString();
            return new OkObjectResult($"OK clientState={clientState}");
        }

The extension will throw this error:

The graph token has no scopes. Ensure your application is properly configured to access the Microsoft Graph.

I've added all the permissions that I need just wonder what else is missing?

I have tried the token binding which gives me a token like this, so the auth has been setup up for this app.

{
  "aud": "https://graph.microsoft.com",
  "iss": "https://sts.windows.net/e021***/",
  "iat": 1547781139,
  "nbf": 1547781139,
  "exp": 1547785039,
  "aio": "42JgYPD7d**",
  "app_displayname": "Test app",
  "appid": "0f889***",
  "appidacr": "1",
  "idp": "https://sts.windows.net/e021***/",
  "oid": "37d***",
  "roles": [
    "Sites.ReadWrite.All",
    "Group.ReadWrite.All",
    "Sites.Manage.All",
    "Files.ReadWrite.All",
    "Notes.ReadWrite.All"
  ],
  "sub": "37dfb***",
  "tid": "e021ec***",
  "uti": "QpQ**",
  "ver": "1.0",
  "xms_tcdt": 147563**
}

Visibility on releases, release notes and CI CD pipelines

This repo lacks of the following things:

  • Github release every time the nuget packages are published. This will help having consistent release notes, tracking whether changes are available or not, tracking PR status…
  • Visibility on the CI CD pipeline (master triggers production packages, dev triggers beta packages?)
  • CD pipeline (doesn't seem in place today) to have automated publishing of the packages, creation of the releases...

Add ability to delete a OneDrive file processed by the External File trigger

It would be good to be able to delete a file in OneDrive from an Azure Function that has been triggered by the same file.

That would allow a user to use OneDrive for dropping files that should be processed in some way but stored in another place, for example Azure Blob Storage, without the need to manually remove files. Dropping files to OneDrive as an integration is easy for a regular PC/smartphone user + easy to develop compared to other alternatives.

NuGet Package has Incorrect Description

The NuGet package for this extension has the following description:

This extension adds bindings for EventGrid

image

Which is clearly not the case :)

It means that this package appears in searches for the EventGrid bindings.

Microsoft Graph Auth Token Binding

The token I am getting from the auth token binding with client credentials seems to be incorrect for some routes.
I am receiving a 500 internal error when I am querying the following route with the token retrived from the binding :

https://graph.microsoft.com/beta/sites/****MySiteId*****/getActivitiesByInterval?startDateTime=2018-09-12T09:59:19.817Z&endDateTime=2018-12-11T00:00:00.000Z&interval=day

If I query the https://graph.microsoft.com/v1.0/users route of microsoft with the token, I have a 200 response so apparently the token only has problems with some routes and client credentials.

I have created a stackoverflow question about that https://stackoverflow.com/questions/54313632/error-500-when-trying-to-query-getactivitiesbyinterval-route-of-microsoft-graph.

Excel Graph bindings are not working if a previous function use Token attribute

Playing around with the sdk beta 3 i found that if a previous function use the Token attribute all the bindings defined for Excel doesnt work.

Environment
Azure Functions v2.
Host 2.2.2
SDK: beta 3

Repro steps

  • create a function to use the Token attribute.
  • example code
public static class Function1
    {

        [FunctionName("Function1")]
        public static async Task<IActionResult> Run1Async(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [Token(
                        Identity = TokenIdentityMode.UserFromToken,
                        UserToken = "%UserToken%",
                        IdentityProvider = "AAD",
                        Resource = "https://graph.microsoft.com")] string token
        )
        {
            return new OkObjectResult(token);
        }


        [FunctionName("Function2")]
        public static async Task<IActionResult> Run2Async(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [Excel(
                Path = "some name",
                TableName ="Table1",
                Identity = TokenIdentityMode.UserFromToken,
                UserToken = "%UserToken%",
                IdentityProvider = "AAD",
                Resource = "https://graph.microsoft.com")] string[][] table
            )
        {
            return new OkObjectResult("OK");
        }
    }
  • This error should be show in the console
    image

workaround

  • Remove function 1 and should work
    image

I think the issue is related on the order on which the extensions are added because if function 1 is declared after function 2 the bindings works

Thanks

Get graphToken for local development

I followed the steps listed in local development section. However, I'm not sure how to get and store a graphToken for local development i.e. running on localhost throws 500. What would be the desired configuration for local.settings.json file for local development? TIA

Client credentials flow breaking

If you attempt to use the client credentials flow, you will get an error stating that your application "was not found in the directory microsoft.com." The "microsoft.com" piece will occur no matter what tenant your application is in.

Early guess is that this is due to us using the common endpoint, when a client credentials flow should be against a proper tenant. You can verify this by attempting the flow manually in postman using the common endpoint.

"Identity requirements not satisfied" message on outlook function creation

I have the following error : "This template requires an AAD configuration for the function app.
App service Authentication / Authorization: not configured" when I try to create an Outlook message webhook handler whereas I have configured the azure active directory authorization.

It seems to be linked with the fact that the AAD I use is on a different tenant. When I use the same tenant than the one of my Function App there is no error message.

I followed microsoft documentation to configure AAD authorization.

Improve error message if user is unauthenticated

If the user is trying to populate a Token binding and the request is unauthenticated, the request returns the following stack trace:
An unhandled exception occurred while processing the request. InvalidOperationException: Error while accessing 'X-MS-TOKEN-AAD-ID-TOKEN': property doesn't exist. Microsoft.Azure.WebJobs.Host.Bindings.Path.BindingTemplateToken+ExpressionToken.Evaluate(IReadOnlyDictionary<string, object> bindingData) in BindingTemplateToken.cs, line 198 InvalidOperationException: Exception binding parameter 'graphToken' Microsoft.Azure.WebJobs.Host.Executors.DelayedException.Throw() in DelayedException.cs, line 27 FunctionInvocationException: Exception while executing function: Functions.ProfilePhotoAPICSharp1 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

We should handle this internal exception and return a message that more clearly indicates that the user isn't authenticated, so we can't populate the Auth token value.

Error while accessing 'X-MS-TOKEN-AAD-ID-TOKEN' from Logic App Custom Connector

I have an Azure Function with a Graph Token input binding that works perfectly from the browser and I also got it working using Postman. I'm now trying to call the function through a Logic App Custom Connector.

I've set up the security in the connector as follows:
image

I've added the custom connector to my logic app and I'm able to successfully sign in with my Azure AD account. However, in runtime I see an internal server error. Looking at the Function app monitoring I notice the Error while accessing 'X-MS-TOKEN-AAD-ID-TOKEN' error message.

As mentioned, Postman is working fine. I'm using the following configuration in Postman to obtain a token.
image

I'm just providing the token in the Authorization header and am not explicitly providing the X-MS-TOKEN-AAD-ID-TOKEN header. Something at the app service level must be taking care of this, but it's a black box to me.

What might be the reason it's not working in the Custom Connector, but is working otherwise directly in the browser or through Postman?

Input binding of GraphWebhookSubscription to string[] broken

When binding GraphWebhookSubscription to a string[], we get an indexing error.

Example
run.csx:

#r "Newtonsoft.Json"

using System.Net;

public static async Task Run(HttpRequest req, string[] existingSubscriptions, IAsyncCollector<string> subscriptionsToDelete, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");
    foreach (var subscription in existingSubscriptions)
    {
        log.Info($"Deleting subscription {subscription}");

        await subscriptionsToDelete.AddAsync(subscription);
    }
}

function.json:

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "authLevel": "anonymous"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "existingSubscriptions",
      "direction": "in",
      "identity": "userFromRequest"
    },
    {
      "type": "graphWebhookSubscription",
      "name": "subscriptionsToDelete",
      "direction": "out",
      "action": "delete",
      "identity": "userFromRequest"
    },
    {
      "type": "http",
      "name": "res",
      "direction": "out"
    }
  ]
}

Error Message: OutlookMessageWebhookDeleter: Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.OutlookMessageWebhookDeleter'. System.Private.CoreLib: The given key was not present in the dictionary.

This looks like a breaking change introduced by beta5 of the runtime, potentially a bug there to investigate.

Support for access token with the token binding (UserFromAccessToken option)

I'm working on the following project:

  • front end application build with SPFx 1.7.0, leveraging the aadHttpClient (if you're not familiar, it bakes in consent, grant, token and adds the Auth Bearer header to any requests providing a fetch client)
  • Azure function (http trigger) secured using the platform authentication options (AAD)
  • Azure function also has a [Token(Identity = TokenIdentityMode.UserFromRequest, Resource = "https://graph.microsoft.com")] string graphToken input binding.

At this point my assumption is that the authentication platform layer (easyAuth) is supposed to take the bearer jwt token coming in, validating it against the configured setting, and passing it as the X-MS-TOKEN-AAD-ID-TOKEN header to the underlying layers.
Then the input binding is looking for that to trade that token in for a token that works for the requested resource.
First question: are those assumptions/this understanding valid?
Second question: For some reason I never get the X-MS-TOKEN-AAD-ID-TOKEN header when the function is called. I tried some workarounds like injecting it manually, to the original request, it feels like a hack but works during local debugging. However this doesn't work on an actual azure function environment. Am I missing any configuration?

The Functions Graph Extension doesn't support the National Clouds.

We have had some customers report that they are seeing errors when using the Graph Extension in the National Clouds.

E.G

image

azure-functions-microsoftgraph-extension\src\MicrosoftGraphBinding\Bindings\O365Constants.cs has this code.

{ ///


/// Base URL used to make any rest API calls
///

public const string GraphBaseUrl = "https://graph.microsoft.com";

All of the national cloud Graph endpoints are documented here.

https://docs.microsoft.com/en-us/graph/deployments#microsoft-graph-and-graph-explorer-service-root-endpoints

It looks like the Graph Extension needs to be updated to support these endpoints as well.

GraphWebhookSubscription attribute binding error

I'm trying to create a function to get all subscription:

        [FunctionName("WebhookTest")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            [GraphWebhookSubscription] string[] subIds
            )
        {
            return new OkObjectResult("OK");
        }

I got this error in the CLI tool:

[1/18/2019 2:47:20 AM] Error indexing method 'WebhookTest.Run'
[1/18/2019 2:47:20 AM] Microsoft.Azure.WebJobs.Host: Error indexing method 'WebhookTest.Run'. System.Private.CoreLib: The given key 'T' was not present in the dictionary.

If I remove the [GraphWebhookSubscription] string[] subIds binding the function is OK.

Error while accessing 'X-MS-TOKEN-AAD-ID-TOKEN'

When I try to use microsoft graph binding I have an exception : "Error while accessing 'X-MS-TOKEN-AAD-ID-TOKEN': property doesn't exist.". I got that exception just by executing my azure function created from the new Microsoft Graph azure function templates.

I have AAD app registered that has been configured with access to the Graph API. Is there something else to do ? Is there something to put in the app settings (the readme on github mentions "The bindings can access the client secret (via appsettings) and use that to perform token exchanges.) ?

System.Private.CoreLib: Exception while executing function: Functions.[funcNameHere]. Microsoft.IdentityModel.Clients.ActiveDirectory: Value cannot be null. Parameter name: authority.

I've followed the instructions for setting the graph token binding while developing locally and am passing in the id_token as the value of the aad token header. Yet I still get:

[07.02.19 23:07:02] System.Private.CoreLib: Exception while executing function: Functions.myFuncName. Microsoft.IdentityModel.Clients.ActiveDirectory: Value cannot be null.
[07.02.19 23:07:02] Parameter name: authority.

What does this mean and how do I fix it?

Thanks!

Docs Don't Contain "How to Contribute" Instructions

A suggestion, rather than an issue.

I have a potential PR, but I'm struggling to test my code locally (against one of my Functions). The unit tests run, but I want to see it working against a real function.

The README.md doesn't have any hints on how to set up local dev environment. Even a few hints/bullets might be useful and raise the chances of PRs being useful.

getting started missing out the metadata generators package

If you want to get started on Visual Studio 2017 today you're missing a rather important step. The functions.json won't have the entries relatives to any of the extensions attributes because the generator is not set up. Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator

I know this is not working today because of an open issue on that package but hopefully it will work at some point Azure/Azure-Functions#690

File input - Microsoft Graph binding doesn't seem to work for worker model

Investigative information

Please provide the following:

  • Timestamp:
  • Function App version (1.0 or 2.0): 2.0
  • Function App name: testing-anything-works & twitch-data-processing
  • Function name(s) (as appropriate): NewStreamDataFile
  • Invocation ID: 73b1d27f-8656-47af-8e66-dbc276b7b805
  • Region: Central US and West US 2

Repro steps

Provide the steps required to reproduce the problem:

Follow https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-microsoft-graph#onedrive-input-code

Expected behavior

Provide a description of the expected behavior.

The binding works

Actual behavior

Provide a description of the actual behavior observed.

2019-01-28T08:19:28.363 [Error] Executed 'Functions.NewStreamDataFile' (Failed, Id=aa0a4fd4-8604-499f-9e8c-59aa2650dc02)
ScriptBinding type System.Byte[] is not supported

Known workarounds

none

Related information

Provide any related information

  • Programming language used: javascript and PowerShell
  • Bindings used: Microsoft Graph (onedrive)

Could not load file or assembly Microsoft.Azure.WebJobs.Extensions.Tokens

Steps to reproduce:

  1. Using the azure portal
  2. Create a new function app
  3. In function App settings, set to beta
  4. In Plaftorm settings, set authentication/authorization to Authentication required, Azure AD, create new Azure AD application.
  5. Add Azure function, select the ProfilePhotoAPICSharp Template. When prompted, install the MSGraph Extension. Wait until installation is completed.
  6. Call the function endpoint. Log shows the following error:

2018-06-22T17:58:06.739 [Error] Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.ProfilePhotoAPICSharp1'. System.Private.CoreLib: Could not load file or assembly 'Microsoft.Azure.WebJobs.Extensions.Tokens, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

A look at kudu shows the file Microsoft.Azure.WebJobs.Extensions.Tokens.dll is present in the /wwwroot/bin folder.

Thanks

Bob

Adding Token binding to a function prevents functions host from initializing.

This error happens whenever I add a Token binding to any function in the App. I hit this same error in 3 different Function Apps, in 3 different tenants, by using the portal. And managed to reproduce locally using "func.exe".

All I had to do to reproduce the error was:

  1. Create a new Functions App in beta version.
  2. Install the Token extension Microsoft.Azure.WebJobs.Extensions.AuthTokens
  3. Add a token parameter to a default HttpTrigger function.

Same steps created the same error using the Functions Portal, or using a VS C# Functions App.

[30-Mar-18 07:50:44] Loaded custom extension: AuthTokenExtensionConfig from 'referenced by: Method='MsGraphBridge.TokenClass.Run', Parameter='graphToken'.'
[30-Mar-18 07:50:44] A ScriptHost error has occurred
[30-Mar-18 07:50:44] Microsoft.Azure.WebJobs.Extensions.Tokens: Method not found: 'Void Microsoft.Azure.WebJobs.Host.Config.FluentBindingRule`1.BindToInput(Microsoft.Azure.WebJobs.IAsyncConverter`2<!0,!!0>)'.
[30-Mar-18 07:50:44] Stopping Host

image

Binding:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "token",
      "name": "token",
      "resource": "https://graph.microsoft.com",
      "identity": "UserFromRequest",
      "direction": "in"
    }
  ]
}

MsGraphBridge.deps.txt

Looking for community contributions?

I'm a big fan of the Microsoft Graph and Azure Functions so I think these extensions are a fabulous pairing. Is the project accepting community contributions? I was considering looking for ways to contribute, possibly with some additional bindings (I'd love to see some Teams bindings) but I wasn't sure if there were already internal updates in the works or an existing backlog? Love to hear some feedback.

Thanks!

Josh

'X-MS-TOKEN-AAD-ID-TOKEN': property doesn't exist

I'm trying to get Graph Token extension working in an Azure function using the instructions in this repo and I keep getting this error:

Error while accessing 'X-MS-TOKEN-AAD-ID-TOKEN': property doesn't exist.

I've checked the documentation 5 times and done a bunch of web searches; need this urgently for a demo. Any chance you can help? Am I missing something easy?
Note I added the extension via the command lines in the article on Github, and deployed via VS Code.

Thanks!

Here is my function.json:

{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "token",
      "direction": "in",
      "name": "graphToken",
      "resource": "https://graph.microsoft.com",
      "identity": "userFromRequest"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

Graph binding with timer trigger

Hi,

Give me advice how to organize my binding to send MS Graph Requests from my azure function which runs by schedule. I tried to use option UserFromId and provided object id of a user from AD which didn't work out.
Eventually what i what to do is to authenticate somehow to execute MSGraph request but not sure how to provide credentials in case on when trigger is schedule.

Add instructions to self-upgrade extension

Currently, due to limitations in the extension process in the portal, users can't upgrade the extension version in the Portal. Instructions, and possibly a script, should be added to the repo so that users who are willing to self-service their upgrade and avoid using the Portal templates can upgrade their Microsoft and Graph extensions manually.

OneDrive streams only supports files up to 4MB

The current method we are using in the Microsoft Graph .NET SDK to upload streams to OneDrive only supports up to 4 MB files. We can utilize their chunked upload to allow larger files.

Obtain token using client credentials for different tenant than the one where function is deployed

Our team is trying to use the Microsoft Graph auth token input binding for an Azure Functions application version 2 implemented in compiled C# on .NET Core 2.2. We want to use a "client credentials" binding, where the function can directly authenticate itself to AAD and interact with the Graph API. We do not want to use delegated permissions, where the function acts on behalf of a user authenticated with AAD.

Our function is deployed in a tenant (tenant ID 43e***) that is distinct from the tenant we want to query with the Graph API (tenant ID 849***).

The auth token binding seems to be affected by three application settings:

  • WEBSITE_AUTH_OPENID_ISSUER: the URL to the tenant from which to obtain an authentication token for the Graph API
  • WEBSITE_AUTH_CLIENT_ID: the client ID used by the function binding to identify the application to the tenant
  • WEBSITE_AUTH_CLIENT_SECRET: the client secret used by the function binding to authenticate to the tenant

We have found that all of these three settings appear to be populated strictly by Azure, itself, specifically for authenticating against the tenant in which the Azure function itself is deployed (43e***). We, however, want to authenticate to a tenant different than the one where the function is deployed, so that the token we get back can be used to query the target tenant (849***). Unfortunately we have found that none of these settings can be overridden in the Application Settings for the Function App.

Is there some other way to specify these pieces of information to the auth token binding so that we can get a token for a tenant that is different than the one on which we have deployed the function?

Remove custom logging category logic

Once a notion of Binding Categories gets added into WebJobs, remove the custom methods that generate the binding category string from this repo.

Version conflict trying to install the AuthTokens package

Just trying to add the AuthTokens nuget package from a new Function created using VS 2017 to use the Auth bindings from the function code.
Running the command - install-package Microsoft.Azure.WebJobs.Extensions.AuthTokens -Version 1.0.0-beta3

Getting this error -

install-package : NU1107: Version conflict detected for Microsoft.Azure.WebJobs. Reference the package directly from the project to
resolve this issue.
MSGraphExplorer -> Microsoft.Azure.WebJobs.Extensions.AuthTokens 1.0.0-beta3 -> Microsoft.Azure.WebJobs (>= 3.0.0-beta5)
MSGraphExplorer -> Microsoft.NET.Sdk.Functions 1.0.13 -> Microsoft.Azure.WebJobs (>= 2.2.0 && < 2.3.0).
At line:1 char:1

  • install-package Microsoft.Azure.WebJobs.Extensions.AuthTokens -Versi ...
  •   + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
    
    

install-package : Package restore failed. Rolling back package changes for 'MSGraphExplorer'.
At line:1 char:1

The error does look legit. Is there a workaround to these? I have validated that "Azure Functions and Web Job Tools" extensions is up to date....

Outlook Message binding returns an error on Functions v2 Runtime and JavaScript.

Error Message

Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.NotifyBoxUsersOfCollabotorChange ---> System.ArgumentException : Object serialized to Bytes. JObject instance expected.
   at Newtonsoft.Json.Linq.JObject.FromObject(Object o,JsonSerializer jsonSerializer)
   at Newtonsoft.Json.Linq.JObject.FromObject(Object o)
   at Microsoft.Azure.WebJobs.Extensions.MicrosoftGraph.Config.Converters.OutlookGenericsConverter`1.Convert(T input)

*Repro Steps

https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-microsoft-graph#outlook-output

Expected Result
The binding should send messages

Actual Result
The error is returned as above.

HttpRequestException when using TokenIdentityMode.UserFromId

I am trying to get a token from Microsoft Graph using UserFromId.

When my function executes locally (from an HttpTrigger), I have the following exception :

System.Net.Http.HttpRequestException: 'The SSL connection could not be established, see inner exception.'

My code is the following :
public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = "gettoken")] HttpRequestMessage request, [Token(UserId = "%UserId%", IdentityProvider = "AAD", Identity = TokenIdentityMode.UserFromId, Resource = "https://graph.microsoft.com")] string graphToken, ILogger log)

I have WEBSITE_AUTH_CLIENT_ID, WEBSITE_AUTH_CLIENT_SECRET, WEBSITE_AUTH_OPENID_ISSUER, WEBSITE_AUTH_SIGNING_KEY settings.
I previously signed in with the user I want on https:///.auth/login/aad
and retrieved the UserId from the user_id field on the response of GET to https:///.auth/me. The user_id is the email of my user. Is it correct ?

So I can't debug my function locally due to this exception.
When I call my function on the portal I have another exception :

Failed to refresh ******** AAD error=Forbidden You do not have permission to view this directory or page.

The "User from ID" identity mode serializes as a wrong value ("userId") into function.json.

[Steps]

  1. Enable Functions 2.0 preview feature, pick the HTTP Trigger template, install the Microsoft Graph extension;
  2. In the Integrate settings page, add the Auth token as a new input;
  3. Pick "User From ID" as the Identity mode;
  4. Fill in other required fields and click on "Save".

[Expected]
The settings should be saved successfully.

[Actual]
An error message is shown:
Function ($HttpTriggerCSharp1) Error: Could not convert 'userId' to TokenIdentityMode. Error converting value "userId" to type 'Microsoft.Azure.WebJobs.TokenIdentityMode'. Path 'identity'. Requested value 'userId' was not found.

[Note]
Looking into function.json, you will see the identity value is "userId", which is wrong and should be "userFromId".

After manually fixing the function.json to have "userFromId" as the identity mode. Everything works as expected.

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.