public async Task <IActionResult> GetThumbNails() { try { if (storageConfig.ImageContainer == string.Empty) { return(BadRequest("Please provide a name for your image container in Azure blob storage.")); } List <string> thumbnailUrls = await StorageHelper.GetThumbNailUrls(storageConfig, new TokenAcquisitionTokenCredential(_tokenAcquisition), this.telemetry, Request.PathBase); return(new ObjectResult(thumbnailUrls)); } catch (MicrosoftIdentityWebChallengeUserException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(new string[] { storageConfig.Scope }, ex.MsalUiRequiredException); return(new OkResult()); } catch (Microsoft.Identity.Client.MsalUiRequiredException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(new string[] { storageConfig.Scope }, ex); return(new OkResult()); } catch (Exception ex) { this.telemetry.TrackException(ex); return(BadRequest(ex.Message)); } }
public async Task <string[]> Get() { try { var teams = await _graphServiceClient.Me.JoinedTeams.Request().GetAsync(); return(teams.Select(t => t.DisplayName).ToArray()); } catch (MsalException ex) { HttpContext.Response.ContentType = "text/plain"; HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await HttpContext.Response.WriteAsync("An authentication error occurred while acquiring a token for downstream API\n" + ex.ErrorCode + "\n" + ex.Message); return(null); } catch (Exception ex) { if (ex.InnerException is MicrosoftIdentityWebChallengeUserException challengeException) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync("user.read".Split(" "), challengeException.MsalUiRequiredException); } else { HttpContext.Response.ContentType = "text/plain"; HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; await HttpContext.Response.WriteAsync("An error occurred while calling the downstream API\n" + ex.Message); } return(null); } }
//[AuthorizeForScopes(Scopes = new[] { "Calendars.Read" })] public async Task <ActionResult <CalendarEventResponse> > Get() { var scopes = new[] { @"https://graph.microsoft.com/Calendars.Read" }; try { HttpClient httpClient = new HttpClient(); var graphUrl = @"https://graph.microsoft.com/v1.0/me/events?$select=subject,bodyPreview,organizer,attendees,start,end,location,categories,sensitivity,showas,responsestatus"; var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await httpClient.GetAsync($"{graphUrl}"); if (response.StatusCode == HttpStatusCode.OK) { var content = await response.Content.ReadAsStringAsync(); var calendarEventResponse = JsonConvert.DeserializeObject <CalendarEventResponse>(content); if (calendarEventResponse.value.Count() == 0) { return(NoContent()); } return(calendarEventResponse); } return(BadRequest($"Http Status Code returned from Graph Api was {response.StatusCode}")); } catch (MicrosoftIdentityWebChallengeUserException ex) { await tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(scopes, ex.MsalUiRequiredException); return(null); } catch (MsalUiRequiredException ex) { await tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(scopes, ex); return(null); } }
private async Task <string> GetAccessTokenForProductsApi() { var accessToken = string.Empty; try { accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(_productApiSettings.Scopes, _azureAdSettings.TenantId); } catch (MsalUiRequiredException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(_productApiSettings.Scopes, ex); } catch (MicrosoftIdentityWebChallengeUserException msChallengeUserExceptionex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(_productApiSettings.Scopes, msChallengeUserExceptionex.MsalUiRequiredException); throw; } return(accessToken); }
public async Task <Event> CallGraphApiOnBehalfOfUserForEvent(string eventId) { string[] scopes = { "user.read", "user.readbasic.all", "mail.send", "calendars.readwrite", "calendars.readwrite.shared", "user.read.all" }; // we use MSAL.NET to get a token to call the API On Behalf Of the current user try { string infernoAPIKey = _configuration.GetValue <string>("InfernoAPIKey"); //ClaimsIdentity claimsIdentity = HttpContext.User.Identity as ClaimsIdentity; string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes); Event newEvent = await CallGraphApiOnBehalfOfUserForEvent(infernoAPIKey, eventId, accessToken /*, claimsIdentity*/); return(newEvent); } catch (MsalUiRequiredException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(scopes, ex); throw ex; } }
public async Task <ActionResult <ProfileItem> > PostProfileItem(ProfileItem profileItem) { HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); profileItem.FirstLogin = false; // This is a synchronous call, so that the clients know, when they call Get, that the // call to the downstream API (Microsoft Graph) has completed. try { User profile = await _graphServiceClient.Me.Request().GetAsync(); profileItem.Id = profile.Id; profileItem.UserPrincipalName = profile.UserPrincipalName; profileItem.GivenName = profile.GivenName; profileItem.Surname = profile.Surname; profileItem.JobTitle = profile.JobTitle; profileItem.MobilePhone = profile.MobilePhone; profileItem.PreferredLanguage = profile.PreferredLanguage; } catch (MsalException ex) { HttpContext.Response.ContentType = "application/json"; HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await HttpContext.Response.WriteAsync(JsonConvert.SerializeObject("An authentication error occurred while acquiring a token for downstream API\n" + ex.ErrorCode + "\n" + ex.Message)); } catch (Exception ex) { if (ex.InnerException is MicrosoftIdentityWebChallengeUserException challengeException) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(_graphOptions.Value.Scopes.Split(' '), challengeException.MsalUiRequiredException); HttpContext.Response.ContentType = "application/json"; HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; await HttpContext.Response.WriteAsync(JsonConvert.SerializeObject("interaction required")); } else { HttpContext.Response.ContentType = "application/json"; HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; await HttpContext.Response.WriteAsync(JsonConvert.SerializeObject("An error occurred while calling the downstream API\n" + ex.Message)); } } _context.ProfileItems.Add(profileItem); await _context.SaveChangesAsync(); return(CreatedAtAction("GetProfileItem", new { id = profileItem.Id }, profileItem)); }
public async Task <string> CallGraphApiOnBehalfOfUser() { string[] scopes = { "user.read" }; // we use MSAL.NET to get a token to call the API On Behalf Of the current user try { string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes); dynamic me = await CallGraphApiOnBehalfOfUser(accessToken); return(me.UserPrincipalName); } catch (MsalUiRequiredException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(scopes, ex); return(string.Empty); } }
public async Task <List <string> > CallGraphApiOnBehalfOfUser() { string[] scopes = { "user.read.all" }; // we use MSAL.NET to get a token to call the API On Behalf Of the current user try { List <string> userList = new List <string>(); string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes); IEnumerable <User> users = await CallGraphApiOnBehalfOfUser(accessToken); userList = users.Select(x => x.UserPrincipalName).ToList(); return(userList); } catch (MsalUiRequiredException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(scopes, ex); throw ex; } }
public async void Post([FromBody] TodoItem todo) { HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); string owner = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; #if ENABLE_OBO // This is a synchronous call, so that the clients know, when they call Get, that the // call to the downstream API (Microsoft Graph) has completed. try { User user = _graphServiceClient.Me.Request().GetAsync().GetAwaiter().GetResult(); string title = string.IsNullOrWhiteSpace(user.UserPrincipalName) ? todo.Title : $"{todo.Title} ({user.UserPrincipalName})"; TodoStore.Add(new TodoItem { Owner = owner, Title = title }); } catch (MsalException ex) { HttpContext.Response.ContentType = "text/plain"; HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await HttpContext.Response.WriteAsync("An authentication error occurred while acquiring a token for downstream API\n" + ex.ErrorCode + "\n" + ex.Message); } catch (Exception ex) { if (ex.InnerException is MicrosoftIdentityWebChallengeUserException challengeException) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(_graphOptions.Value.Scopes.Split(' '), challengeException.MsalUiRequiredException); } else { HttpContext.Response.ContentType = "text/plain"; HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; await HttpContext.Response.WriteAsync("An error occurred while calling the downstream API\n" + ex.Message); } } #endif }
public async Task <IActionResult> Get() { try { User user = await _graphServiceClient.Me.Request().GetAsync(); var userDisplayName = user.DisplayName; var apiResponse = new ApiResponse { GreetingFromApi = $"Hello {userDisplayName}!" }; return(Ok(apiResponse)); } catch (MsalException ex) { HttpContext.Response.ContentType = "text/plain"; HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await HttpContext.Response.WriteAsync("An authentication error occurred while acquiring a token for downstream API\n" + ex.ErrorCode + "\n" + ex.Message); } catch (Exception ex) { if (ex.InnerException is MicrosoftIdentityWebChallengeUserException challengeException) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(_graphOptions.Value.Scopes.Split(' '), challengeException.MsalUiRequiredException); } else { HttpContext.Response.ContentType = "text/plain"; HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; await HttpContext.Response.WriteAsync("An error occurred while calling the downstream API\n" + ex.Message); } } return(BadRequest()); }
public async Task <dynamic> CallGraphApiOnBehalfOfUser() { string[] scopes = { "GroupMember.Read.All" }; dynamic response; // we use MSAL.NET to get a token to call the API On Behalf Of the current user try { string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes); GraphHelper.Initialize(accessToken); var groups = await GraphHelper.GetMembershipAsync(); response = groups; } catch (MsalUiRequiredException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(scopes, ex); return("interaction required"); } return(response); }