// GET api/CallGraph public async Task <IEnumerable <string> > GetAsync() { List <string> userList = new List <string>(); string accessToken = null; AuthenticationResult result = null; _tokenAcquisition = new TokenAcquisition(new AuthenticationConfig()); try { result = await _tokenAcquisition.GetUserTokenOnBehalfOfAsync(requestedScopes).ConfigureAwait(false); accessToken = result.AccessToken; if (accessToken == null) { // An unexpected error occurred. return(null); } IEnumerable <User> users = await CallGraphApiOnBehalfOfUser(accessToken); userList = users.Select(x => x.UserPrincipalName).ToList(); return(userList); } catch (Exception ex) { throw ex; } }
// GET: api/AccessCaApi/GetAll public async Task <List <string> > GetAll() { var scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope"); if (scopeClaim == null || (!scopeClaim.Value.ContainsAny("access_as_user"))) { throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'access_as_user' or scope claim not found" }); } AuthenticationResult result = null; _tokenAcquisition = new TokenAcquisition(new AuthenticationConfig()); // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, for your application, to return an error immediately to the user and have the user initiate the retry. bool retry = false; int retryCount = 0; do { retry = false; try { result = await _tokenAcquisition.GetUserTokenOnBehalfOfAsync(caResourceIdScope); } catch (MsalUiRequiredException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync((caResourceIdScope), ex, HttpContext.Current.Response); throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden }); } } while ((retry == true) && (retryCount < 1)); /* * You can now use this access token to accesss our Conditional-Access protected Web API using On-behalf-of * Use this code below to call the downstream Web API OBO */ string oboAccessToken = result.AccessToken; _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", oboAccessToken); List <string> lstUsers = new List <string>(); HttpResponseMessage response = await _httpClient.GetAsync(_TodoListDownstreamBaseAddress + "/api/CallGraph"); if (response != null && response.StatusCode == HttpStatusCode.OK) { string content = response.Content.ReadAsStringAsync().Result; lstUsers = JsonConvert.DeserializeObject <List <string> >(content); return(lstUsers); } throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}."); }
// GET: api/ConditionalAccess public async Task <string> Get() { var scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope"); if (scopeClaim == null || (!scopeClaim.Value.ContainsAny("access_as_user"))) { throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'access_as_user' or scope claim not found" }); } AuthenticationResult result = null; _tokenAcquisition = new TokenAcquisition(new AuthenticationConfig()); // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, for your application, to return an error immediately to the user and have the user initiate the retry. bool retry = false; int retryCount = 0; do { retry = false; try { result = await _tokenAcquisition.GetUserTokenOnBehalfOfAsync(caResourceIdScope); return("protected API successfully called"); } catch (MsalUiRequiredException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync((caResourceIdScope), ex, HttpContext.Current.Response); throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden }); } } while ((retry == true) && (retryCount < 1)); /* * You can now use this access token to accesss our Conditional-Access protected Web API using On-behalf-of * Use this code below to call the downstream Web API OBO * * string oboAccessToken = result.AccessToken; * private HttpClient httpClient = new HttpClient(); * httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); * HttpResponseMessage response = await httpClient.GetAsync(WebAPI2HttpEndpoint (App ID URI + "/endpoint"); */ }
public static async Task <UserProfile> CallGraphAPIOnBehalfOfUser() { UserProfile profile = null; string accessToken = null; AuthenticationResult result = null; // In the case of a transient error, retry once after 1 second, then abandon. // Retrying is optional. It may be better, for your application, to return an error immediately to the user and have the user initiate the retry. bool retry = false; int retryCount = 0; do { retry = false; try { //_tokenAcquisition = new TokenAcquisition(SetOptions.SetMicrosoftIdOptions(), SetOptions.SetConClientAppOptions()); _tokenAcquisition = new TokenAcquisition(new AuthenticationConfig()); result = await _tokenAcquisition.GetUserTokenOnBehalfOfAsync(requestedScopes); accessToken = result.AccessToken; } catch (MsalException ex) { if (ex.ErrorCode == SERVICE_UNAVAILABLE) { // Transient error, OK to retry. retry = true; retryCount++; Thread.Sleep(1000); } } } while ((retry == true) && (retryCount < 1)); if (accessToken == null) { // An unexpected error occurred. return(null); } // // Call the Graph API and retrieve the user's profile. // HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, graphUserUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage response = await client.SendAsync(request); // // Return the user's profile. // if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); profile = JsonConvert.DeserializeObject <UserProfile>(responseString); return(profile); } // An unexpected error occurred calling the Graph API. Return a null profile. return(null); }