コード例 #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
        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);
            }
        }
コード例 #3
0
        private static bool AddUserToGroup(string userId, List <string> groups)
        {
            var res  = true;
            var body = new GraphGroupAdd(userId);

            foreach (string groupId in groups)
            {
                AdalResponse serverResponse = null;
                var          uri            = string.Format("https://graph.microsoft.com/v1.0/groups/{0}/members/$ref", groupId);
                serverResponse = CallGraph(uri, body);
                if (!serverResponse.Successful)
                {
                    res = false;
                }
            }
            return(res);
        }
コード例 #4
0
        public static IEnumerable <GraphMemberRole> GetDirectoryRoles(string upn)
        {
            AdalResponse serverResponse = null;
            var          rolesUri       = string.Format("{0}/{1}/users/{2}/memberOf", Settings.GraphResource, Settings.GraphApiVersion, upn);

            serverResponse = CallGraph(rolesUri);
            var list = new List <GraphMemberRole>();

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

            return(list);
        }
コード例 #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 static AdalResponse CallGraph(string uri, dynamic postContent = null, bool isUpdate = false, string graphResource = null)
        {
            string resource = (graphResource != null) ? graphResource : Settings.GraphResource;

            var res = new AdalResponse
            {
                Successful = true
            };
            HttpResponseMessage response = null;

            try
            {
                AuthenticationResult authResult = null;

                // Get auth token
                var task = Task.Run(async() => {
                    authResult = await AuthenticateApp(resource);
                });
                task.Wait();

                string accessToken = authResult.AccessToken;

                var bearer = new AuthenticationHeaderValue("Bearer", accessToken);

                //getting inconsistent results (chunked vs not chunked) with async calls - switching to webclient/sync
                if (postContent != null)
                {
                    using (var httpClient = new HttpClient())
                    {
                        httpClient.Timeout = TimeSpan.FromSeconds(300);
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                        httpClient.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString());
                        httpClient.DefaultRequestHeaders.GetValues("client-request-id").Single();
                        string serialized = JsonConvert.SerializeObject(postContent);

                        HttpContent content = new StringContent(serialized, Encoding.UTF8, "application/json");

                        if (isUpdate)
                        {
                            var method  = new HttpMethod("PATCH");
                            var request = new HttpRequestMessage(method, uri)
                            {
                                Content = content
                            };

                            response = httpClient.SendAsync(request).Result;
                        }
                        else
                        {
                            response = httpClient.PostAsync(uri, content).Result;
                        }
                        res.ResponseContent = response.Content.ReadAsStringAsync().Result;
                        res.StatusCode      = response.StatusCode;
                        res.Message         = response.ReasonPhrase;
                        if (!response.IsSuccessStatusCode)
                        {
                            res.Successful = false;
                            var serverError        = JsonConvert.DeserializeObject <GraphError>(res.ResponseContent);
                            var reason             = (response == null ? "N/A" : response.ReasonPhrase);
                            var serverErrorMessage = (serverError.Error == null) ? "N/A" : serverError.Error.Message;
                            res.Message = string.Format("Server response: {0}. Server detail: {1})", reason, serverErrorMessage);
                            return(res);
                        }
                    }
                }
                else
                {
                    using (var webClient = new WebClient())
                    {
                        webClient.Headers.Add("Authorization", bearer.ToString());
                        webClient.Headers.Add("client-request-id", Guid.NewGuid().ToString());

                        res.ResponseContent = webClient.DownloadString(uri);
                    }
                }
                return(res);
            }
            catch (Exception ex)
            {
                res.Successful = false;
                res.Message    = ex.Message;
                return(res);
            }
        }
コード例 #7
0
        public static async Task <string> SendInvitation(GuestRequest request, string profileUrl, PreAuthDomain domainSettings = null)
        {
            var displayName = string.Format("{0} {1}", request.FirstName, request.LastName);

            var useCustomEmailTemplate = false;
            var redemptionSettings     = Settings.SiteRedemptionSettings;
            var memberType             = MemberType.Guest;

            //use domain custom setting if exists, else use global site config setting
            if (domainSettings != null)
            {
                redemptionSettings = domainSettings.DomainRedemptionSettings;
                //domainSettings.InviteTemplateContent;
                memberType = domainSettings.MemberType;

                if (!string.IsNullOrEmpty(domainSettings.InviteTemplateId))
                {
                    useCustomEmailTemplate = true;
                }
            }

            AdalResponse serverResponse = null;

            try
            {
                // Setup invitation
                var             inviteEndPoint = string.Format("{0}/{1}/invitations", Settings.GraphResource, Settings.GraphApiVersion);
                GraphInvitation invitation     = new GraphInvitation();
                invitation.InvitedUserDisplayName  = displayName;
                invitation.InvitedUserEmailAddress = request.EmailAddress;
                invitation.InviteRedirectUrl       = profileUrl;
                invitation.SendInvitationMessage   = (!Settings.UseSMTP);
                invitation.InvitedUserType         = memberType.ToString();

                if (useCustomEmailTemplate && invitation.SendInvitationMessage && domainSettings.InviteTemplateContent.TemplateContent != null)
                {
                    invitation.InvitedUserMessageInfo = new InvitedUserMessageInfo
                    {
                        CustomizedMessageBody = domainSettings.InviteTemplateContent.TemplateContent
                    };
                }

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

                if (domainSettings != null)
                {
                    if (domainSettings.Groups != null && domainSettings.Groups.Count > 0)
                    {
                        var groupsAdded = AddUserToGroup(responseData.InvitedUser.Id, domainSettings.Groups);
                        //todo: log or notify re the negative
                    }
                }

                if (Settings.UseSMTP)
                {
                    var emailSubject = Settings.InvitationEmailSubject.Replace("{{orgname}}", Settings.InvitingOrganization);

                    string body = FormatEmailBody(responseData, redemptionSettings, domainSettings.InviteTemplateContent);
                    SendViaSMTP(emailSubject, body, invitation.InvitedUserEmailAddress);
                }

                return(responseData.Status);
            }
            catch (Exception ex)
            {
                var reason = (serverResponse == null ? "N/A" : serverResponse.ResponseContent);

                return(string.Format("Error: {0}<br>Server response: {1}", ex.Message, reason));
            }
        }
コード例 #8
0
ファイル: InviteManager.cs プロジェクト: furena/bigcatAlpha
        /// <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);
            }
        }