Created
April 7, 2018 14:18
-
-
Save programmersommer/8fb049b96b86168bb17532601e2596c9 to your computer and use it in GitHub Desktop.
Azure Function as Token service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
using Microsoft.Azure.Devices; | |
using Microsoft.Azure.Devices.Common.Security; | |
using System.Globalization; | |
using System.Security.Cryptography; | |
using System.Text; | |
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) | |
{ | |
string deviceid = req.GetQueryNameValuePairs() | |
.FirstOrDefault(q => string.Compare(q.Key, "deviceid", true, CultureInfo.InvariantCulture) == 0).Value; | |
string hash = req.GetQueryNameValuePairs() | |
.FirstOrDefault(q => string.Compare(q.Key, "hash", true, CultureInfo.InvariantCulture) == 0).Value; | |
if (String.IsNullOrEmpty(deviceid)) return req.CreateResponse(HttpStatusCode.BadRequest, "device id missing"); | |
if (String.IsNullOrEmpty(hash)) return req.CreateResponse(HttpStatusCode.BadRequest, "hash missing"); | |
var resourceUri ="ArduinoDemoHub.azure-devices.net/devices/"+deviceid; | |
// taken from IoT Hub user with Connect devices rights (not from Device Explorer) | |
var connectionString = "HostName=ArduinoDemoHub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=cuYBKc42lfJr4oSRGQGQ8IiKWxGQkLre7rprZDZ/ths="; | |
var registryManager = RegistryManager.CreateFromConnectionString(connectionString); | |
var device = await registryManager.GetDeviceAsync(deviceid); | |
var key = device.Authentication.SymmetricKey.PrimaryKey; | |
HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes("somerandomkeyKJBWyfy4gski")); | |
var hashedkey = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(key))); | |
if (hashedkey!=hash) return req.CreateResponse(HttpStatusCode.BadRequest, "wrong hash"); | |
SharedAccessSignatureBuilder sasBuilder = new SharedAccessSignatureBuilder() | |
{ | |
Key = key, | |
Target = resourceUri, | |
TimeToLive = TimeSpan.FromDays(Convert.ToDouble(7)) | |
}; | |
var SAS = sasBuilder.ToSignature(); | |
return req.CreateResponse(HttpStatusCode.OK, SAS); | |
} | |
// add dependency in project.json file | |
// { | |
// "frameworks": { | |
// "net46":{ | |
// "dependencies": { | |
// "Microsoft.Azure.Devices": "1.4.1" | |
// } | |
// } | |
// } | |
// } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment