예제 #1
0
        /// <inheritdoc />
        public async Task AuthenticateOutboundRequestAsync(HttpRequestMessage request, string tenantId)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(tenantId), $"Invalid {nameof(tenantId)}.");

            const string BearerPrefix            = "Bearer";
            const string ReplaceString           = "{tenant}";
            const string TokenAuthorityMicrosoft = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token";
            const string Resource = @"https://graph.microsoft.com";

            var tokenLink = TokenAuthorityMicrosoft.Replace(ReplaceString, tenantId);

            var context = new AuthenticationContext(tokenLink);
            var creds   = new ClientCredential(this.AppId, this.AppSecret);

            AuthenticationResult result;

            try
            {
                result = await context.AcquireTokenAsync(Resource, creds).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Debug.Write($"Acquire token failed {ex.Message}");

                throw;
            }

            request.Headers.Authorization = new AuthenticationHeaderValue(BearerPrefix, result.AccessToken);
        }
        /// <inheritdoc />
        public async Task AuthenticateOutboundRequestAsync(HttpRequestMessage request, string tenantId)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(tenantId), $"Invalid {nameof(tenantId)}.");

            const string BearerPrefix            = "Bearer";
            const string ReplaceString           = "{tenant}";
            const string TokenAuthorityMicrosoft = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token";
            const string Resource = @"https://graph.microsoft.com/.default";

            var           tokenLink  = TokenAuthorityMicrosoft.Replace(ReplaceString, tenantId);
            OAuthResponse authResult = null;

            try
            {
                using (var httpClient = new HttpClient())
                {
                    var result = await httpClient.PostAsync(tokenLink, new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("grant_type", "password"),
                        new KeyValuePair <string, string>("username", this.userName),
                        new KeyValuePair <string, string>("password", this.password),
                        new KeyValuePair <string, string>("scope", Resource),
                        new KeyValuePair <string, string>("client_id", this.appId),
                        new KeyValuePair <string, string>("client_secret", this.appSecret),
                    })).ConfigureAwait(false);

                    if (!result.IsSuccessStatusCode)
                    {
                        throw new Exception("Failed to generate user token.");
                    }

                    var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

                    authResult = JsonConvert.DeserializeObject <OAuthResponse>(content);

                    request.Headers.Authorization = new AuthenticationHeaderValue(BearerPrefix, authResult.Access_Token);
                }
            }
            catch (Exception ex)
            {
                this.GraphLogger.Error(ex, $"Failed to generate user token for user: {this.userName}");
                throw;
            }

            this.GraphLogger.Info($"Generated OAuth token. Expires in {authResult.Expires_In / 60}  minutes.");
        }