Exemple #1
0
        private async Task OnExecutingAsync(HttpRequest request, Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            // Extract token from header, return 'Unauthorized' error if the token is null.
            string token = string.Empty;

            if (request.Headers.ContainsKey("Authorization") && request.Headers["Authorization"][0].StartsWith("Bearer "))
            {
                token = request.Headers["Authorization"][0].Substring("Bearer ".Length);
            }
            else
            {
                request.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                throw new HttpRequestException("Unauthorized");
            }

            // Get Azure AD env settings
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            _backendUrl    = config["BackendUrl"];
            _instance      = config["AzureAd:Instance"];
            _tenantId      = config["AzureAd:TenantId"];
            _clientId      = config["AzureAd:ClientId"];
            _clientSecret  = config["AzureAd:ClientSecret"];
            _allowedScopes = config["AzureAd:AllowedScopes"].Split(',');

            // Validate token (authorization)
            string audience = $"api://{_clientId}";
            await TokenValidation.VerifyUserHasAnyAcceptedScope(token, _instance, _tenantId, _clientId, audience, _allowedScopes, new CancellationToken());

            // Request token
            string[] requestedScopes   = new string[] { $"api://{config["AzureAd:BackendClientId"]}/{_scope}" };
            var      accessTokenResult = await _authToken.GetOnBehalfOf(
                _tenantId,
                _clientId,
                _clientSecret,
                token,
                requestedScopes);

            // Inject token in auth header
            _httpClient.SetAuthenticationHeader("Bearer", accessTokenResult.AccessToken);
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);

            string[] scopes = _configuration["AzureAd:RequestedScopes"].Split(',')
                              .Select(x => $"api://{_configuration["AzureAd:MidtierClientId"]}/{x}").ToArray();

            // Request token
            var accessTokenResult = _authToken.GetOnBehalfOf(
                _configuration["AzureAd:TenantId"],
                _configuration["AzureAd:ClientId"],
                _configuration["AzureAd:ClientSecret"],
                Request.Headers["X-MS-TOKEN-AAD-ID-TOKEN"],
                scopes
                ).ContinueWith((r) =>
            {
                return(r.Result);
            }).Result;

            // Inject token in auth header
            _httpClient.SetAuthenticationHeader("Bearer", accessTokenResult.AccessToken);
        }