Skip to content
This repository has been archived by the owner on Feb 17, 2021. It is now read-only.

Commit

Permalink
feat: authenticate function using MSI
Browse files Browse the repository at this point in the history
  • Loading branch information
coderbyheart committed Jan 29, 2020
1 parent dc975c7 commit f19bc01
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
3 changes: 3 additions & 0 deletions azuredeploy.json
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,9 @@
"name": "[concat(parameters('appName'), 'WebSite')]",
"location": "[parameters('location')]",
"kind": "functionapp",
"identity": {
"type": "SystemAssigned"
},
"dependsOn": [
"[resourceId('Microsoft.Web/serverfarms', concat(parameters('appName'), 'ServerFarm'))]",
"[resourceId('Microsoft.Storage/storageAccounts', parameters('AppStorageName'))]"
Expand Down
32 changes: 25 additions & 7 deletions listDevices/index.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,39 @@
import { AzureFunction, Context, HttpRequest } from '@azure/functions'
import { IotHubClient } from '@azure/arm-iothub'
import * as msRestNodeAuth from '@azure/ms-rest-nodeauth'

const listDevices: AzureFunction = async (
context: Context,
req: HttpRequest,
): Promise<void> => {
context.log('HTTP trigger function processed a request.')
const name = req.query.name || (req.body && req.body.name)
context.log({ req })
try {
// See https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#obtaining-tokens-for-azure-resources
const msiTokenRes = await msRestNodeAuth.loginWithAppServiceMSI({
msiEndpoint: process.env.MSI_ENDPOINT || '',
msiSecret: process.env.MSI_SECRET || '',
})
console.log(msiTokenRes)

const iotHubClient = new IotHubClient(
msiTokenRes,
process.env.AZURE_SUBSCRIPTION_ID || '',
)
const iotHubs = await iotHubClient.iotHubResource.listBySubscription()

if (name) {
context.res = {
// status: 200, /* Defaults to 200 */
body: `Hello ${req.query.name || req.body.name}`,
headers: {
'Content-Type': 'application/json; charset=uft-8',
},
isRaw: true,
body: JSON.stringify(iotHubs),
}
} else {
} catch (error) {
context.res = {
status: 400,
body: 'Please pass a name on the query string or in the request body',
status: 500,
isRaw: true,
body: JSON.stringify(error),
}
}
}
Expand Down

0 comments on commit f19bc01

Please sign in to comment.