示例#1
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var scopes = new string[] { "https://graph.microsoft.com/.default", "offline_access" };

            if (req.Method == "POST" && req.Form.ContainsKey("code"))
            {
                var code = req.Form["code"].FirstOrDefault();

                var app = ConfidentialClientApplicationBuilder.Create(_settings.ClientId)
                          .WithClientSecret(_settings.ClientSecret)
                          .WithTenantId(_settings.Tenant)
                          .WithRedirectUri(req.GetDisplayUrl())
                          .Build();

                var cache = new TokenCacheHelper(AzureApp.CacheFileDir);
                cache.EnableSerialization(app.UserTokenCache);

                _ = await app.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync();

                return(new OkObjectResult("The app is authorized to perform operations on behalf of your account."));
            }

            var url = new StringBuilder();

            url.Append($"https://login.microsoftonline.com/{_settings.Tenant}/oauth2/v2.0/authorize?");
            url.Append($"client_id={_settings.ClientId}&");
            url.Append($"response_type=code&");
            url.Append($"redirect_uri={req.GetEncodedUrl()}&");
            url.Append($"response_mode=form_post&");
            url.Append($"scope={WebUtility.UrlEncode(string.Join(" ", scopes))}&");
            return(new RedirectResult(url.ToString(), false));
        }
        public async Task <GraphServiceClient> Create()
        {
            var app = ConfidentialClientApplicationBuilder.Create(_azureAppSettings.ClientId)
                      .WithClientSecret(_azureAppSettings.ClientSecret)
                      .WithTenantId(_azureAppSettings.Tenant)
                      .Build();

            TokenCacheHelper.EnableSerialization(app.UserTokenCache);

            var accounts = await app.GetAccountsAsync();

            var authProvider = new DelegateAuthenticationProvider(async(requestMessage) =>
            {
                var result = await app.AcquireTokenSilent(new string[] { "https://graph.microsoft.com/.default" }, accounts.FirstOrDefault()).ExecuteAsync();
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
            });

            return(new GraphServiceClient(authProvider));
        }