问题
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?
回答1:
What I did:
- Added an "authorize" API that handles general-purpose authorization against foreign authorities. This API returns my own JWT with my own custom claims that lasts for a some limited amount of time.
- Changed all of my other API's to use my custom JWT.
Advantages:
- Super easy to test locally. I just add #if DEBUG sections to the authorization API to skip normal authorization and give me a JWT of my design.
- I can put whatever I want in the claim, so I use it as a cache to reduce external authorization calls.
回答2:
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:
- Inject the ClaimPrincipal into your function
- Check if the user is authenticated (e.g., principal.Identity.IsAuthenticated) and return UnauthorizedResult if they are not.
- 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.
- 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.
来源:https://stackoverflow.com/questions/49421027/developing-azure-functions-locally