예제 #1
0
        public async Task <IActionResult> Blob()
        {
            var scopes = new string[] { "https://storage.azure.com/user_impersonation" };

            try
            {
                var accessToken =
                    await _tokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, scopes);

                // create a blob on behalf of the user
                TokenCredential    tokenCredential    = new TokenCredential(accessToken);
                StorageCredentials storageCredentials = new StorageCredentials(tokenCredential);

                // replace the URL below with your storage account URL
                CloudBlockBlob blob = new CloudBlockBlob(new Uri("https://blobstorageazuread.blob.core.windows.net/sample-container/Blob1.txt"), storageCredentials);
                await blob.UploadTextAsync("Blob created by Azure AD authenticated user.");

                ViewData["Message"] = "Blob successfully created";
                return(View());
            }
            catch (MsalUiRequiredException ex)
            {
                if (CanbeSolvedByReSignInUser(ex))
                {
                    AuthenticationProperties properties = BuildAuthenticationPropertiesForIncrementalConsent(scopes, ex);
                    return(Challenge(properties));
                }
                else
                {
                    throw;
                }
            }
        }
        public async Task <IActionResult> Create()
        {
            string userId      = User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value;
            string tenantId    = User.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
            string clientState = Guid.NewGuid().ToString();

            // Initialize the GraphServiceClient.
            var graphClient = await GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
            {
                string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(
                    HttpContext, new[] { Infrastructure.Constants.ScopeMailRead });
                return(result);
            });

            Subscription newSubscription = new Subscription();

            try
            {
                // Create a subscription.
                // The `Resource` property targets the `users/{user-id}` or `users/{user-principal-name}` path (not `me`) when using application permissions.
                // The NotificationUrl requires the `https` protocol and supports custom query parameters.

                newSubscription = await graphClient.Subscriptions.Request().AddAsync(new Subscription
                {
                    Resource        = $"users/{userId}/mailFolders('Inbox')/messages",
                    ChangeType      = "created",
                    NotificationUrl = appSettings.NotificationUrl,
                    ClientState     = clientState,
                    //ExpirationDateTime = DateTime.UtcNow + new TimeSpan(0, 0, 4230, 0) // current maximum lifespan for messages
                    ExpirationDateTime = DateTime.UtcNow + new TimeSpan(0, 0, 15, 0)     // shorter duration useful for testing
                });

                // Verify client state, then store the subscription ID and client state to validate incoming notifications.
                if (newSubscription.ClientState == clientState)
                {
                    // This sample temporarily stores the subscription data, but production apps will likely use some method of persistent storage.
                    // This sample stores the client state to validate the subscription, the tenant ID to reuse tokens, and the user ID to filter
                    // messages to display by user.
                    subscriptionStore.SaveSubscriptionInfo(newSubscription.Id,
                                                           newSubscription.ClientState,
                                                           userId,
                                                           tenantId);
                }
                else
                {
                    ViewBag.Message = "Warning! Mismatched client state.";
                }
            }
            catch (Exception e)
            {
                // If a tenant admin hasn't granted consent, this operation returns an Unauthorized error.
                // This sample caches the initial unauthorized token, so you'll need to start a new browser session.
                ViewBag.Message = BuildErrorMessage(e);
                return(View("Error"));
            }

            return(View("Subscription", newSubscription));
        }
예제 #3
0
        public async Task <IActionResult> Index()
        {
            var    scopes = new string[] { $"{_configuration["FhirServerAudience"].TrimEnd('/')}/.default" };
            string accessToken;

            try
            {
                accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, scopes);
            }
            catch (MsalUiRequiredException ex)
            {
                AuthenticationProperties properties = AuthenticationPropertiesBuilder.BuildForIncrementalConsent(scopes, HttpContext, ex);
                return(Challenge(properties));
            }

            var            client         = GetClientAsync(accessToken);
            Bundle         result         = null;
            List <Patient> patientResults = new List <Patient>();

            try
            {
                if (!string.IsNullOrEmpty(Request.Query["ct"]))
                {
                    string cont = Request.Query["ct"];
                    result = client.Search <Patient>(new string[] { $"ct={cont}" });
                }
                else
                {
                    result = client.Search <Patient>();
                }

                if (result.Entry != null)
                {
                    foreach (var e in result.Entry)
                    {
                        patientResults.Add((Patient)e.Resource);
                    }
                }

                if (result.NextLink != null)
                {
                    ViewData["NextLink"] = result.NextLink.PathAndQuery;
                }
            }
            catch (Exception e)
            {
                ViewData["ErrorMessage"] = e.Message;
            }

            return(View(patientResults));
        }
예제 #4
0
        public async Task <IActionResult> Profile()
        {
            var accessToken =
                await tokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, new[] { Constants.ScopeUserRead });

            var me = await graphApiOperations.GetUserInformation(accessToken);

            var photo = await graphApiOperations.GetPhotoAsBase64Async(accessToken);

            ViewData["Me"]    = me;
            ViewData["Photo"] = photo;

            return(View());
        }
예제 #5
0
        public async Task <IActionResult> Profile()
        {
            // Initialize the GraphServiceClient.
            var graphClient = await GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
            {
                string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(
                    HttpContext, new[] { Constants.ScopeUserRead });
                return(result);
            }, webOptions.GraphApiUrl);

            // Get user profile info.
            var me = await graphClient.Me.Request().GetAsync();

            ViewData["Me"] = me;

            try
            {
                // Get user photo
                var photoStream = await graphClient.Me.Photo.Content.Request().GetAsync();

                byte[] photoByte = ((MemoryStream)photoStream).ToArray();
                ViewData["Photo"] = Convert.ToBase64String(photoByte);
            }
            catch (System.Exception)
            {
                ViewData["Photo"] = null;
            }

            return(View());
        }
예제 #6
0
        public async Task <IActionResult> GetAction(string resourceType, string resourceId)
        {
            var    scopes = new string[] { $"{_configuration["FhirImportService:Audience"].TrimEnd('/')}/.default" };
            string accessToken;

            try
            {
                accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, scopes);
            }
            catch (MsalUiRequiredException ex)
            {
                AuthenticationProperties properties = AuthenticationPropertiesBuilder.BuildForIncrementalConsent(scopes, HttpContext, ex);
                return(Challenge(properties));
            }

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_configuration["FhirServerUrl"]);
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");

                HttpResponseMessage result = await client.GetAsync($"/{resourceType}/{resourceId}");

                result.EnsureSuccessStatusCode();

                ViewData["ResourceJson"] = await result.Content.ReadAsStringAsync();
            }

            return(View("Index"));
        }
예제 #7
0
        public async Task <User> GetUser()
        {
            User user = httpContextAccessor.HttpContext.Session.GetUser();

            if (user != null)
            {
                return(user);
            }

            string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(httpContextAccessor.HttpContext, new[] { Constants.ScopeUserRead });

            var userInformation = await graphApiOperations.GetUserInformation(accessToken) as JObject;

            user = userInformation.ToObject <User>();

            User dbUser = db.Users.Find(user.Id);

            if (dbUser == null)
            {
                db.Users.Add(user);
                db.SaveChanges();
            }
            else
            {
                user = dbUser;
            }

            httpContextAccessor.HttpContext.Session.Set("User", user);

            return(user);
        }
예제 #8
0
 private Graph::GraphServiceClient GetGraphServiceClient(string[] scopes)
 {
     return(GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
     {
         string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(
             HttpContext, scopes);
         return result;
     }, webOptions.GraphApiUrl));
 }
        public async Task <IActionResult> Blob()
        {
            var scopes = new string[] { "https://storage.azure.com/user_impersonation" };

            try
            {
                var accessToken =
                    await _tokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, scopes);

                ViewData["Message"] = await CreateBlob(accessToken);

                return(View());
            }
            catch (MsalUiRequiredException ex)
            {
                AuthenticationProperties properties = BuildAuthenticationPropertiesForIncrementalConsent(scopes, ex);
                return(Challenge(properties));
            }
        }
        public async Task <IActionResult> Index2()
        {
            string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, new[] { "User.Read", "Directory.Read.All" });

            User me = await _service.GetMeAsync(accessToken);

            IList <Group> groups = await _service.GetMyGroupsAsync(accessToken);

            ViewData["Me"]     = me;
            ViewData["Groups"] = groups;

            return(View());
        }
예제 #11
0
        public async Task <IActionResult> Index()
        {
            string accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, new[] { Constants.ScopeUserRead, Constants.ScopeDirectoryReadAll });

            User me = await graphService.GetMeAsync(accessToken);

            var photo = await graphService.GetMyPhotoAsync(accessToken);

            IList <Group> groups = await graphService.GetMyMemberOfGroupsAsync(accessToken);

            ViewData["Me"]     = me;
            ViewData["Photo"]  = photo;
            ViewData["Groups"] = groups;

            return(View());
        }
예제 #12
0
        // Get information about the changed messages and send to browser via SignalR.
        // A production application would typically queue a background job for reliability.
        private async Task GetChangedMessagesAsync(IEnumerable <Notification> notifications)
        {
            List <MessageViewModel> messages = new List <MessageViewModel>();

            foreach (var notification in notifications)
            {
                if (notification.ResourceData.ODataType != "#Microsoft.Graph.Message")
                {
                    continue;
                }

                SubscriptionStore subscription = subscriptionStore.GetSubscriptionInfo(notification.SubscriptionId);

                // Set the claims for ObjectIdentifier and TenantId, and
                // use the above claims for the current HttpContext
                HttpContext.User = ClaimsPrincipalExtension.FromTenantIdAndObjectId(subscription.TenantId, subscription.UserId);

                // Initialize the GraphServiceClient.
                var graphClient = await GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
                {
                    string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(
                        HttpContext, new[] { Infrastructure.Constants.ScopeMailRead });
                    return(result);
                });

                MessageRequest request = new MessageRequest(graphClient.BaseUrl + "/" + notification.Resource, graphClient, null);
                try
                {
                    messages.Add(new MessageViewModel(await request.GetAsync(), subscription.UserId));
                }
                catch (ServiceException se)
                {
                    string errorMessage = se.Error.Message;
                    string requestId    = se.Error.InnerError.AdditionalData["request-id"].ToString();
                    string requestDate  = se.Error.InnerError.AdditionalData["date"].ToString();

                    logger.LogError($"RetrievingMessages: { errorMessage } Request ID: { requestId } Date: { requestDate }");
                }
            }

            if (messages.Count > 0)
            {
                NotificationService notificationService = new NotificationService();
                await notificationService.SendNotificationToClient(this.notificationHub, messages);
            }
        }
예제 #13
0
        //[Authorize(Policy = "DirectoryViewerRole")]
        //[Authorize(Policy = "SubGroup2-Part1Only")]
        //[Authorize(Roles = AppRoles.DirectoryViewers)]
        public async Task <IActionResult> Groups()
        {
            string[] scopes = new[] { GraphScopes.DirectoryReadAll };

            GraphServiceClient graphServiceClient = GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
            {
                string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(
                    HttpContext, scopes);
                return(result);
            }, webOptions.GraphApiUrl);

            var groups = await graphServiceClient.Me.MemberOf.Request().GetAsync();

            ViewData["Groups"] = groups.CurrentPage;

            return(View());
        }
예제 #14
0
        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.GetAccessTokenOnBehalfOfUser(HttpContext, scopes);

                dynamic me = await CallGraphApiOnBehalfOfUser(accessToken);

                return(me.userPrincipalName);
            }
            catch (MsalUiRequiredException ex)
            {
                _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeader(HttpContext, scopes, ex);
                return(string.Empty);
            }
        }
예제 #15
0
        public async Task <IActionResult> AboutMe()
        {
            var    identity           = User.Identity as ClaimsIdentity; // Azure AD V2 endpoint specific
            string preferred_username = identity.Claims.FirstOrDefault(c => c.Type == "preferred_username")?.Value;

            ViewData["FhirServerUrl"] = _configuration["FhirServerUrl"];
            ViewData["UPN"]           = preferred_username;

            var scopes = new string[] { $"{_configuration["FhirServerAudience"].TrimEnd('/')}/.default" };

            try
            {
                var accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, scopes);

                ViewData["token"] = accessToken;
                return(View());
            }
            catch (MsalUiRequiredException ex)
            {
                AuthenticationProperties properties = AuthenticationPropertiesBuilder.BuildForIncrementalConsent(scopes, HttpContext, ex);
                return(Challenge(properties));
            }
        }
예제 #16
0
 protected async Task <string> GetAccessToken(string scope = "https://management.azure.com/user_impersonation")
 {
     return(await _tokenAcquisition.GetAccessTokenOnBehalfOfUser(
                HttpContext,
                new[] { scope }));
 }