Giter Club home page Giter Club logo

vitalybibikov / azureextensions.functiontoken Goto Github PK

View Code? Open in Web Editor NEW
11.0 1.0 5.0 57 KB

Extension Attribute to Azure Functions v3, that allows to obtain ClaimsPrincipal on every request. Currently supports key load from Azure B2C by jwks_uri and simple JsonWebKey. Pluggable on Azure Function Startup

Home Page: https://www.nuget.org/packages/AzureExtensions.FunctionToken/

License: Apache License 2.0

C# 100.00%
azure azure-functions azureb2c claimsprincipal webjobs authentication input-binding oidc firebase firebase-auth

azureextensions.functiontoken's Introduction

AzureExtensions.FunctionToken

Extension Attribute to Azure Functions v3, that allows to obrain ClaimsPrincipal on every request. Currently supports key load from Azure B2C by jwks_uri and simple JsonWebKey. Pluggable into Azure Function Startup

The extension allows you to use custom tokens in Azure Functions v3.

Step 1.

  1. Add the nuget AzureExtensions.FunctionToken
  2. Add to Startup file the following code. Currently, accepts simple JWK tokens or tokens loaded out of Azure B2C

           builder.AddAzureFunctionsToken(new TokenSinginingKeyOptions()
            {
                SigningKey = new JsonWebKey("your key"),
                Audience = "your audience",
                Issuer = "your issuer"
            });

OR B2C

            builder.AddAzureFunctionsToken(new TokenAzureB2COptions()
            {
                //AzureB2CSingingKeyUri = new Uri("https://yourapp.b2clogin.com/yourapp.onmicrosoft.com/discovery/v2.0/keys?p=yourapp-policy"),
                Audience = "your audience",
                Issuer = "your issuer"
            });

OR Firebase

            builder.AddAzureFunctionsToken(new FireBaseOptions()
            {
                GoogleServiceAccountJsonUri = new Uri("%uri-to-storage-with-secret-json-from-google")
            });

  1. Add it to Azure Function:
    public class Example
    {
        [FunctionName("Example")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            [FunctionToken] FunctionTokenResult token,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            return (ActionResult) new OkObjectResult($"Hello, {token}");
        }
    }
  1. By, default AuthLevel.Authorized level is used, but you can also specify AuthLevel.AllowAnonymous
        [FunctionName("Example")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestMessage req,
            [FunctionToken(AuthLevel.AllowAnonymous)] FunctionTokenResult token,
            ILogger log)
        {
                log.LogInformation("C# HTTP trigger function processed a request.");
                return new OkObjectResult($"Hello, {token}");
        }}
  1. Currently, AF 2.0 does not support invocation to Short Circuit, so in order to return proper 401 code when UnAuthorized, the function should be wrapped in Handler: Wrap/WrapAsync. This one will return 401 if token is invalid:
        [FunctionName("Example")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestMessage req,
            [FunctionToken(AuthLevel.Authorized)] FunctionTokenResult token,
            ILogger log)
        {
            return await Handler.WrapAsync(token,async () =>
            {
                log.LogInformation("C# HTTP trigger function processed a request.");
                return new OkObjectResult($"Hello, {token}");
            });
        }
  1. Also, roles as a set of strings are supported: In order the role to be validated, role ClaimTypes.Role of System.Security should be presented in a token It is also mapped to type: http://schemas.microsoft.com/ws/2008/06/identity/claims/role

     [FunctionName("Example")]
     public async Task<IActionResult> Run(
         [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestMessage req,
         [FunctionToken("Manager", "Worker")] FunctionTokenResult token,
         ClaimsPrincipal principal,
         ILogger log)
     {
         var identity = token.Principal.Claims.First(x => x.Type == ClaimTypes.NameIdentifier);
         return await Handler.WrapAsync(token,async () =>
         {
             log.LogInformation("C# HTTP trigger function processed a request.");
             return new OkObjectResult($"Hello, {token}");
         });
     }
    

ClaimsPrincipal can be injected, when

       builder.Services.AddHttpContextAccessor();

attached via:

       var injectedPrincipal = req.HttpContext.User;
  1. That's it

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.