Пример #1
0
        public async Task <IActionResult> SetOnBehalfToken()
        {
            var requestId = Guid.NewGuid().ToString();

            _logger.LogInformation($"RequestID:{requestId} SetupController_SetOnBehalfToken called.");

            try
            {
                var userId = User.FindFirst(AzureAdConstants.ObjectIdClaimType)?.Value;

                var testToken = await _graphAuthProvider.GetUserAccessTokenAsync(userId, true);

                Guard.Against.NullOrEmpty(testToken, $"RequestID:{requestId} SetupController_SetOnBehalfToken token is empty.");

                return(NoContent());
                //return Ok(testToken); // TODO: For testing only, remove this line and uncomment the previous line before relese
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestID:{requestId} SetupController_SetOnBehalfToken error: {ex.Message}");
                var errorResponse = JsonErrorResponse.BadRequest($"RequestID:{requestId} SetupController_SetOnBehalfToken error: {ex.Message}", requestId);

                return(BadRequest(errorResponse));
            }
        }
        public string Token()
        {
            var userIdentity = (ClaimsIdentity)User.Identity;
            var identifier   = userIdentity.FindFirst(Startup.ObjectIdentifierType)?.Value + "." + userIdentity.FindFirst(Startup.TenantIdType)?.Value;
            var accessToken  = _authProvider.GetUserAccessTokenAsync(identifier).Result;

            return(accessToken);
        }
        // Get an authenticated Microsoft Graph Service client.
        public GraphServiceClient GetAuthenticatedClient(string userId)
        {
            _graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
                                                      async requestMessage =>
            {
                // Passing tenant ID to the sample auth provider to use as a cache key
                var accessToken = await _authProvider.GetUserAccessTokenAsync(userId);

                // Append the access token to the request
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            }));

            return(_graphClient);
        }
Пример #4
0
        public GraphServiceClient GetAuthenticatedGraphClient(ClaimsIdentity userIdentity) =>
        new GraphServiceClient(new DelegateAuthenticationProvider(
                                   async requestMessage =>
        {
            // Get user's id for token cache.
            var identifier = userIdentity.FindFirst(Startup.ObjectIdentifierType)?.Value + "." + userIdentity.FindFirst(Startup.TenantIdType)?.Value;

            // Passing tenant ID to the sample auth provider to use as a cache key
            var accessToken = await _authProvider.GetUserAccessTokenAsync(identifier);

            // Append the access token to the request
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            // This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove.
            requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample");
        }));
Пример #5
0
        // Get an authenticated Microsoft Graph Service client.
        public GraphServiceClient GetAuthenticatedClient(string userId)
        {
            _graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
                                                      async requestMessage =>
            {
                // Passing tenant ID to the sample auth provider to use as a cache key
                var accessToken = await _authProvider.GetUserAccessTokenAsync(userId);

                // Append the access token to the request
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove.
                requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample");
            }));

            return(_graphClient);
        }
        // Get an authenticated Microsoft Graph Service client.
        public GraphServiceClient GetAuthenticatedClient(ClaimsIdentity userIdentity)
        {
            _graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
                                                      async requestMessage =>
            {
                // Get user's id for token cache.
                var identifier = userIdentity.FindFirst(Startup.ObjectIdentifierType)?.Value + "." + userIdentity.FindFirst(Startup.TenantIdType)?.Value;

                // Passing tenant ID to the sample auth provider to use as a cache key
                var accessToken = await _authProvider.GetUserAccessTokenAsync(identifier);

                // Append the access token to the request
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            }));

            return(_graphClient);
        }
Пример #7
0
        // Get an authenticated Microsoft Graph Service client.
        public GraphServiceClient GetAuthenticatedClientForUser()
        {
            ClaimsPrincipal principal = HttpContext.Current.User as ClaimsPrincipal;
            string          userId    = principal.FindFirst(Startup.ObjectIdentifierType)?.Value;

            graphClient = new GraphServiceClient("https://graph.microsoft.com/beta", new DelegateAuthenticationProvider(
                                                     async requestMessage =>
            {
                // Passing tenant ID to the sample auth provider to use as a cache key
                var accessToken = await authProvider.GetUserAccessTokenAsync(userId);

                // Append the access token to the request
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            }));

            return(graphClient);
        }
        public GraphClientOnBehalfContext(
            IGraphAuthProvider authProvider,
            IUserContext userContext)
        {
            Guard.Against.Null(authProvider, nameof(authProvider));
            Guard.Against.Null(userContext, nameof(userContext));
            _authProvider = authProvider;
            _userContext  = userContext;

            // Initialize the graph client given the chosen context
            if (_graphServiceClient == null)
            {
                _graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider(
                                                                 async requestMessage =>
                {
                    // Passing tenant ID to the auth provider to use as a cache key
                    var accessToken = await _authProvider.GetUserAccessTokenAsync(User.FindFirst(AzureAdConstants.ObjectIdClaimType)?.Value, true);

                    // Append the access token to the request
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                }));
            }
        }
Пример #9
0
        private string GetAccessToken(string assertion)
        {
            string updatedAccessToken = AsyncUtil.RunSync(async() => await _authProvider.GetUserAccessTokenAsync(assertion));

            return(_memoryCache.GetOrCreate(assertion, o => AsyncUtil.RunSync(async() => await _authProvider.GetUserAccessTokenAsync(assertion))));
        }
Пример #10
0
        // Load user's profile in formatted JSON.
        public async Task <CompositeGraphObject> GetUserJson(string email, string search = null)
        {
            if (email == null)
            {
                return(null);
            }

            CompositeGraphObject compositeGraphObject = this.memoryCache.Get("compositeGraphObject") as CompositeGraphObject;

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

            var    user        = HttpContext.Current.User as ClaimsPrincipal;
            string userId      = user.FindFirst(Startup.ObjectIdentifierType)?.Value;
            var    accessToken = await authProvider.GetUserAccessTokenAsync(userId);

            HttpClient httpClient = new HttpClient(new HttpClientHandler());

            httpClient.BaseAddress = new Uri(@"https://graph.microsoft.com/beta/");
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            try
            {
                User me = await GeObjectFromGraph <User>(httpClient, "me");

                Organization organization = await GeObjectFromGraph <Organization>(httpClient, "organization");

                //List<DriveItem> driveItems = await GetListOfObjectsFromGraph<DriveItem>(httpClient, "me/drive/root/children");
                List <DriveItem> driveSharedItems =
                    await GetListOfObjectsFromGraph <DriveItem>(httpClient, "me/drive/sharedWithMe");

                //SHAREPOINT SHARED DOCUMENTS
                //List<List> siteLists = await GetListOfObjectsFromGraph<List>(httpClient, "sites/root/lists");
                //List sharedDocuments = siteLists.FirstOrDefault(sr => sr.Name.Equals("Shared Documents"));
                //List<DriveItem> sharedDocumentItems = await GetListOfObjectsFromGraph<DriveItem>(httpClient, "sites/root/lists/" + sharedDocuments.Id + "/items");

                List <Message> messages = await GetListOfObjectsFromGraph <Message>(httpClient, "me/messages");

                List <Event> events = await GetListOfObjectsFromGraph <Event>(httpClient, "me/events");

                List <Contact> contacts = await GetListOfObjectsFromGraph <Contact>(httpClient, "me/contacts");

                List <OnenoteSection> oneNoteSections =
                    await GetListOfObjectsFromGraph <OnenoteSection>(httpClient, "me/onenote/sections");

                //List<OnenotePage> onenotePages = await GetListOfObjectsFromGraph<OnenotePage>(httpClient, "me/onenote/pages");

                Planner planner = await GeObjectFromGraph <Planner>(httpClient, "me/planner/");

                List <PlannerPlan> plannerPlan =
                    await GetListOfObjectsFromGraph <PlannerPlan>(httpClient, "me/planner/plans");

                List <PlannerTask> plannerTasks =
                    await GetListOfObjectsFromGraph <PlannerTask>(httpClient, "me/planner/tasks");

                List <Group> joinedTeams = await GetListOfObjectsFromGraph <Group>(httpClient, "me/joinedTeams");

                string      searchFor  = search ?? "Wojciech";
                List <User> foundUsers =
                    await GetListOfObjectsFromGraph <User>(httpClient, "me/people?$search=" + searchFor);

                List <User> teamMembers =
                    await GetListOfObjectsFromGraph <User>(httpClient, "groups/" + joinedTeams[0].Id + "/members");

                List <TeamChannel> teamChannels =
                    await GetListOfObjectsFromGraph <TeamChannel>(httpClient,
                                                                  "teams/" + joinedTeams[0].Id + "/channels");

                List <TeamChannelTab> channelTabs = await GetListOfObjectsFromGraph <TeamChannelTab>(httpClient,
                                                                                                     "teams/" + joinedTeams[0].Id + "/channels/" + teamChannels[0].Id + "/tabs");

                //List<object> applications = await GetListOfObjectsFromGraph<object>(httpClient, "applications");
                List <AppRoleAssignment> appRoleAssignments =
                    await GetListOfObjectsFromGraph <AppRoleAssignment>(httpClient, "me/appRoleAssignments");

                var picture = await GetPictureBase64(userId);

                compositeGraphObject = new CompositeGraphObject()
                {
                    Organization    = organization,
                    Planner         = planner,
                    TeamChannelTabs = channelTabs,
                    User            = me,
                    Events          = events,
                    OnenoteSections = oneNoteSections,
                    Messages        = messages,
                    PlannerPlans    = plannerPlan,
                    //OnenotePages = onenotePages,
                    Contacts           = contacts,
                    AppRoleAssignments = appRoleAssignments,
                    PlannerTasks       = plannerTasks,
                    TeamChannels       = teamChannels,
                    DriveItems         = driveSharedItems,
                    FoundUsers         = foundUsers,
                    JoinedTeams        = joinedTeams,
                    TeamMembers        = teamMembers,
                    Picture            = picture
                };

                this.memoryCache.Add(new CacheItem("compositeGraphObject", compositeGraphObject),
                                     new CacheItemPolicy()
                {
                    SlidingExpiration = TimeSpan.FromHours(5), AbsoluteExpiration = DateTimeOffset.MaxValue
                });

                return(compositeGraphObject);
            }
            catch (ServiceException e)
            {
                switch (e.Error.Code)
                {
                case "RequestResourceNotFound":
                case "ResourceNotFound":
                case "ErrorItemNotFound":
                case "itemNotFound":
                    return(null);

                case "ErrorInvalidUser":
                    return(null);

                case "AuthenticationFailure":
                    return(null);

                case "TokenNotFound":
                    //await httpContext.ChallengeAsync();
                    return(null);

                default:
                    return(null);
                }
            }
            catch (Exception e)
            {
                return(null);
            }
        }