예제 #1
0
        public static RoleResponse GetDirectoryRoles(string upn)
        {
            var res = new RoleResponse();

            AdalResponse serverResponse = null;
            var          rolesUri       = string.Format("{0}/{1}/users/{2}/memberOf", Settings.GraphResource, Settings.GraphApiVersion, upn);

            serverResponse   = AdalUtil.CallGraph(rolesUri);
            res.Successful   = serverResponse.Successful;
            res.ErrorMessage = serverResponse.Message;

            var list = new List <GraphMemberRole>();

            if (serverResponse.Successful)
            {
                JObject        data  = JObject.Parse(serverResponse.ResponseContent);
                IList <JToken> roles = data["value"].ToList();
                foreach (var role in roles)
                {
                    var item = JsonConvert.DeserializeObject <GraphMemberRole>(role.ToString());
                    list.Add(item);
                }
            }

            res.Roles = list;
            return(res);
        }
예제 #2
0
        public InviteManager(BatchQueueItem batch)
        {
            _user       = new CacheUser(batch.InvitingUserId, batch.UserSourceHostName);
            _profileUrl = batch.ProfileUrl;
            AuthenticationResult res = null;
            var task = Task.Run(async() => {
                res = await AdalUtil.AuthenticateApp(null, _user);
            });

            task.Wait();
            _accessToken = res.AccessToken;
        }
예제 #3
0
        private async Task <GraphInvitation> SendGraphInvitationAsync(GraphInvitation invitation, List <GroupObject> groups, string inviterResponseEmailAddr = null, InviteTemplate mailTemplate = null, string accessToken = null)
        {
            AdalResponse    serverResponse = null;
            GraphInvitation responseData   = new GraphInvitation();

            try
            {
                var inviteEndPoint = string.Format("{0}/{1}/invitations", Settings.GraphResource, Settings.GraphApiVersion);

                // Invite user. Your app needs to have User.ReadWrite.All or Directory.ReadWrite.All to invite
                serverResponse = AdalUtil.CallGraph(inviteEndPoint, invitation, false, null, _user, accessToken);
                responseData   = JsonConvert.DeserializeObject <GraphInvitation>(serverResponse.ResponseContent);
                if (responseData.id == null)
                {
                    responseData.ErrorInfo = string.Format("Error: Invite not sent - API error: {0}", serverResponse.Message);
                    return(responseData);
                }

                if (groups.Count > 0)
                {
                    var groupsAdded = AddUserToGroup(responseData.InvitedUser.Id, groups);
                    if (!groupsAdded.Success)
                    {
                        var resErrors = string.Join(", ", groupsAdded.Responses.Where(r => !r.Successful).Select(r => r.Message));
                        responseData.ErrorInfo += string.Format("\n\rOne or more groups failed while assigning to user \"{0}\" ({1})", responseData.InvitedUserEmailAddress, resErrors);
                    }
                }

                if (Settings.UseSMTP)
                {
                    mailTemplate = mailTemplate ?? Settings.CurrSiteConfig.InviteTemplateContent;

                    var emailSubject = mailTemplate.SubjectTemplate.Replace("{{InvitingOrgName}}", Settings.CurrSiteConfig.InvitingOrg);

                    string body = FormatEmailBody(responseData, inviterResponseEmailAddr, mailTemplate);
                    SendViaSMTP(emailSubject, body, invitation.InvitedUserEmailAddress);
                }


                var request = await GuestRequestRules.GetUserAsync(invitation.InvitedUserEmailAddress);

                request.InvitationResult = responseData;
                await GuestRequestRules.UpdateAsync(request);

                return(responseData);
            }
            catch (Exception ex)
            {
                var reason = (serverResponse == null ? "N/A" : serverResponse.ResponseContent);
                responseData.ErrorInfo = string.Format("Error: {0}<br>Server response: {1}", ex.Message, reason);
                return(responseData);
            }
        }
예제 #4
0
        public GraphUtil()
        {
            AuthenticationResult authResult = AdalUtil.AuthenticateApp().Result;
            string accessToken = authResult.AccessToken;

            _client = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                return(Task.FromResult(0));
            }));
        }
예제 #5
0
        private static GroupAddResult AddUserToGroup(string userId, List <GroupObject> groups)
        {
            var res = new GroupAddResult()
            {
                Success = true
            };
            var          body           = new GraphGroupAdd(userId);
            AdalResponse serverResponse = null;

            foreach (GroupObject group in groups)
            {
                var uri = string.Format("https://graph.microsoft.com/v1.0/groups/{0}/members/$ref", group.GroupId);
                serverResponse = AdalUtil.CallGraph(uri, body);
                res.Responses.Add(serverResponse);
                if (!serverResponse.Successful)
                {
                    res.Success = false;
                }
            }
            return(res);
        }
예제 #6
0
        public GraphUtil(CacheUser user = null)
        {
            _user = user;
            AuthenticationResult authResult = null;
            // Get auth token
            var task = Task.Run(async() => {
                authResult = await AdalUtil.AuthenticateApp(null, user);
            });

            task.Wait();

            string accessToken = authResult.AccessToken;

            _client = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                return(Task.FromResult(0));
            }));
        }
예제 #7
0
        /// <summary>
        /// GraphInvitation is a model from https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/invitation
        /// Do not alter
        /// </summary>
        /// <param name="invitation">The GraphInvitation object transmitted to the B2B Guest API</param>
        /// <param name="groups">Azure AD groups to assign the guest user to</param>
        /// <param name="inviterResponseEmailAddr"></param>
        /// <param name="mailTemplate"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        private async Task <GuestRequest> SendGraphInvitationAsync(GraphInvitation invitation, List <GroupObject> groups, GuestRequest request, string inviterResponseEmailAddr = null, InviteTemplate mailTemplate = null, string accessToken = null)
        {
            AdalResponse    serverResponse = null;
            GraphInvitation responseData   = new GraphInvitation();

            try
            {
                var inviteEndPoint = string.Format("{0}/{1}/invitations", Settings.GraphResource, Settings.GraphApiVersion);

                // Invite user. Your app needs to have User.ReadWrite.All or Directory.ReadWrite.All to invite
                serverResponse = AdalUtil.CallGraph(inviteEndPoint, invitation, false, null, _user, accessToken);

                responseData             = JsonConvert.DeserializeObject <GraphInvitation>(serverResponse.ResponseContent);
                request.InvitationResult = responseData;
                request.Status           = responseData.Status;

                if (responseData.id == null)
                {
                    //API call failed - put the request back in the queue
                    responseData.ErrorInfo   = string.Format("Error: Invite not sent - API error: {0}", serverResponse.Message);
                    request.InvitationResult = responseData;
                    request.Disposition      = Disposition.Pending;
                }
                else
                {
                    //invitation API call successful
                    if (responseData.Status.Substring(0, 5) == "Error")
                    {
                        //API call was successful but something failed while trying to process the request - put the request back in the queue
                        request.Disposition = Disposition.Pending;
                    }
                    else
                    {
                        //check to see if groups should be assigned
                        if (groups.Count > 0)
                        {
                            try
                            {
                                var groupsAdded = AddUserToGroup(responseData.InvitedUser.Id, groups);
                                if (!groupsAdded.Success)
                                {
                                    //group assignment failed
                                    var resErrors = string.Join(", ", groupsAdded.Responses.Where(r => !r.Successful).Select(r => r.Message));
                                    var msg       = string.Format("\n\rOne or more groups failed while assigning to user \"{0}\" ({1})", responseData.InvitedUserEmailAddress, resErrors);
                                    request.PostProcessingStatus += msg;
                                }
                            }
                            catch (Exception groupEx)
                            {
                                //group assignment errored
                                var msg = string.Format("\n\rAn error occured while assigning a group to user \"{0}\" ({1})", responseData.InvitedUserEmailAddress, groupEx.Message);
                                Logging.WriteToAppLog(msg, EventLogEntryType.Warning, groupEx);
                                request.PostProcessingStatus += msg;
                            }
                        }

                        //check to see if custom mail should be sent
                        if (Settings.UseSMTP)
                        {
                            try
                            {
                                mailTemplate = mailTemplate ?? Settings.CurrSiteConfig.InviteTemplateContent;

                                var emailSubject = mailTemplate.SubjectTemplate.Replace("{{InvitingOrgName}}", Settings.CurrSiteConfig.InvitingOrg);

                                string body = FormatEmailBody(responseData, inviterResponseEmailAddr, mailTemplate);
                                SendViaSMTP(emailSubject, body, invitation.InvitedUserEmailAddress);
                                request.MailSent = true;
                            }
                            catch (Exception mailEx)
                            {
                                var msg = string.Format("\n\rSending invitation failed for user \"{0}\" ({1})", responseData.InvitedUserEmailAddress, mailEx.Message);
                                Logging.WriteToAppLog(msg, EventLogEntryType.Warning, mailEx);
                                request.PostProcessingStatus += msg;
                            }
                        }
                    }
                }

                //all attempts complete, UPDATE GuestRequest
                await GuestRequestRules.UpdateAsync(request);

                return(request);
            }
            catch (Exception ex)
            {
                var reason = (serverResponse == null ? "N/A" : serverResponse.ResponseContent);
                responseData.ErrorInfo   = string.Format("Error: {0}<br>Server response: {1}", ex.Message, reason);
                request.InvitationResult = responseData;

                //UPDATE GuestRequest
                await GuestRequestRules.UpdateAsync(request);

                return(request);
            }
        }