Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Developing Azure functions locally

I am leading a large team of azure functions developers. So, most of the examples quoted by Microsoft using the azure web interface don't work for me. I am developing Azure functions locally using emulators to save some costs. I publish all my functions through visual studio into my integration environment.

I am developing a bunch of azure functions that need the api gateway to handle the authentication workflows using Azure AD B2C. Now, there's no api gateway emulator or an Azure AD B2C emulator that I can run locally. My authentication workflows involve intercepting requests to the api, redirecting them to AD B2C for authentication and the subsequent addition of the auth-token to the http header and then invoking the http-triggered azure functions.

Now, the question becomes, how do I test authentication workflows? How can I setup the api gateway to register my functions running locally in visual studio as api endpoint for my api gateway in the cloud?

like image 845
horatius Avatar asked Mar 22 '18 05:03

horatius


1 Answers

Here is another alternative if you are developing a SPA that uses Azure-AD or Azure B2C via Easy Auth, which will do your JWT token validation for you and leaving you to do the following:

Your SPA is going to get a token even locally so do the following:

  1. Inject the ClaimPrincipal into your function
  2. Check if the user is authenticated (e.g., principal.Identity.IsAuthenticated) and return UnauthorizedResult if they are not.
  3. Check for an issuer claim. If the principal has one, it went through Express Auth., your JWT token was validated by it and you can get your claims from it immediately.
  4. If there is no issuer, it's local development and you can turn to the header and pull the JWT token out yourself and get your claims. You could also IFDEF this out for conditional build so that your doubly sure that it's local development.

Here is some example code of pulling the JWT token out of the header (HttpRequest is injected into each function):

private JwtSecurityToken ReadJwtTokenFromHeader(HttpRequest req)
{
   if (req.Headers.ContainsKey("Authorization"))
   {
       var authHeader = req.Headers["Authorization"];
       var headerValue = AuthenticationHeaderValue.Parse(authHeader);

       var handler = new JwtSecurityTokenHandler();
       return handler.ReadJwtToken(headerValue.Parameter);
   }

   return null;
}

Note: This requires the System.IdentityModel.Tokens.Jwt NuGet package to use JwtSecurityTokenHandler.

like image 152
David Yates Avatar answered Sep 30 '22 15:09

David Yates