Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Function Custom Authentication

I have been looking for a way for azure function custom authentication. I could see many out of the box authentication including function keys, AD authentication, and other identity providers. My scenario is to authenticate azure function only for those logged into the web application using a custom user name and password, which I have stored in the database. Is there an out of the box implementation for that? Any help would be much appreciated

like image 772
Vijayanath Viswanathan Avatar asked Mar 04 '23 13:03

Vijayanath Viswanathan


1 Answers

I came across a similar problem as I wanted to authenticate requests using JWT access tokens issued by an external OAuth server. There’s no convenient middleware that lets you do this, but you can create a custom input binding that lets you inject something like a ClaimsPrincipal into the function definition, e.g.

[FunctionName("ExampleHttpFunction")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "example")] HttpRequest req, 
    ILogger log, 
    [AccessToken] ClaimsPrincipal principal)
{
    log.LogInformation($"Request received for {principal.Identity.Name}.");
    return new OkResult();
}

This separates authentication from the function itself, making it easier to test, though you'll still need to add in authorization checks and explicitly return 40x status codes.

The binding SDK isn't that well documented and you'll need to wire together half a dozen different classes to make it work, but I have written up the detail here: Custom token authentication in Azure Functions using bindings. The code itself is posted on GitHub – just replace the code in the IValueProvider implementation with your own authentication method.

I hope this helps. The alternative, I guess, is to write some boiler plate code that you add into every function?

like image 144
Ben Morris Avatar answered Mar 19 '23 12:03

Ben Morris