Skip to content

Instantly share code, notes, and snippets.

@bcnzer
Created November 25, 2017 03:41
Show Gist options
  • Select an option

  • Save bcnzer/44dfea610975780abd6b7277eb040138 to your computer and use it in GitHub Desktop.

Select an option

Save bcnzer/44dfea610975780abd6b7277eb040138 to your computer and use it in GitHub Desktop.
Simple Azure Function based on the HTTP Trigger sample code, with the addition of the token validation call
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
namespace SpotterPowerlifting.Functions
{
public static class AuthTest
{
[FunctionName("AuthTest")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
ClaimsPrincipal principal;
if ((principal = await Security.ValidateTokenAsync(req.Headers.Authorization)) == null)
{
return req.CreateResponse(HttpStatusCode.Unauthorized);
}
// parse query parameter
string name = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
.Value;
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();
// Set name to query string or body data
name = name ?? data?.name;
return name == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}
}
}
@cottsak
Copy link
Copy Markdown

cottsak commented May 17, 2019

What packages do you need for this? Because as a csx func it's failing to recognise Security.ValidateTokenAsync() and i can't seem to make it work in a netcoreapp2.1 proj app either?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment