/// <summary> /// Get Classic Site Collections from SharePoint Online Tenant /// </summary> /// <param name="siteUrl"></param> /// <param name="userName"></param> /// <param name="password"></param> private static void getClassicSiteCollections(string siteUrl, string userName, SecureString password) { var credentials = new SharePointOnlineCredentials(userName, password); ClientContext ctx = new ClientContext(siteUrl); ctx.Credentials = credentials; //ctx.ExecutingWebRequest Tenant tenant = new Tenant(ctx); //var ac = ctx.GetAccessToken(); // ctx.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; var authCookie = credentials.GetAuthenticationCookie(new Uri(siteUrl)); var headers = new Dictionary <string, string>() { { "Cookie", authCookie } }; var allSites = CallSharePointOnlineAPI($@"https://brgrp-admin.sharepoint.com/_vti_bin/client.svc/lists/GetByTitle('DO_NOT_DELETE_SPLIST_TENANTADMIN_AGGREGATED_SITECOLLECTIONS')/items?$top=10&$filter=IsGroupConnected", HttpMethod.Get, null, headers, null, null).GetAwaiter().GetResult(); SPOSitePropertiesEnumerable siteProps = tenant.GetSitePropertiesFromSharePoint("0", true); //tenant.LegacyAuthProtocolsEnabled = false; ctx.Load(siteProps); ctx.ExecuteQuery(); Console.WriteLine("*************************************************"); Console.WriteLine("Total Classic Collections: " + siteProps.Count.ToString()); foreach (var site in siteProps) { Console.WriteLine("{0} - {1}", site.Title, site.Template.ToString()); } }
protected static string GetFormDigest() { Console.WriteLine("Logging into {0} as {1}", webUri, userName); string password = Environment.GetEnvironmentVariable("SPPWD"); SecureString securePassword; if (password == null) { Console.WriteLine("Enter password"); securePassword = GetPassword(); Console.WriteLine(""); } else { securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } } var credentials = new SharePointOnlineCredentials(userName, securePassword); var authCookie = credentials.GetAuthenticationCookie(new Uri(webUri), true); Console.WriteLine("Full authCookie {0}", authCookie); return(authCookie.TrimStart("SPOIDCRL=".ToCharArray())); }
public SPService(string username, string password, string url) { using (ClientContext ctx = new ClientContext(url)) { var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } var onlineCredentials = new SharePointOnlineCredentials(username, securePassword); ctx.Credentials = onlineCredentials; web = ctx.Web; ctx.Load(web); ctx.ExecuteQuery(); //ctx.GetFormDigestDirect().DigestValue var authCookie = onlineCredentials.GetAuthenticationCookie(new Uri(url)); //var fedAuthString = authCookie.TrimStart("SPOIDCRL=".ToCharArray()); webinfo = new WebInfo { Title = web.Title, ErrorMessage = "", DigestInfo = authCookie.ToString() }; context = ctx; } }
internal static UserProfileService GetUserProfileService(string profileSiteUrl, string sPoAuthUserName, string sPoAuthPassword) { try { string webServiceExt = "_vti_bin/userprofileservice.asmx"; string adminWebServiceUrl = string.Empty; adminWebServiceUrl = $"{profileSiteUrl.TrimEnd('/')}/{webServiceExt}"; LogMessage("Initializing SPO web service " + adminWebServiceUrl, EventLogEntryType.Information, ServiceEventID.SharePointOnlineError); SecureString securePassword = GetSecurePassword(sPoAuthPassword); SharePointOnlineCredentials onlineCred = new SharePointOnlineCredentials(sPoAuthUserName, securePassword); string authCookie = onlineCred.GetAuthenticationCookie(new Uri(profileSiteUrl)); CookieContainer authContainer = new CookieContainer(); authContainer.SetCookies(new Uri(profileSiteUrl), authCookie); var userProfileService = new UserProfileService(); userProfileService.Url = adminWebServiceUrl; userProfileService.CookieContainer = authContainer; return(userProfileService); } catch (Exception ex) { LogMessage("Error initiating connection to profile web service in SPO " + ex.Message, EventLogEntryType.Error, ServiceEventID.SharePointOnlineError); return(null); } }
private bool AuthenticateAdministrator(string login, string password) { try { var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } var onlineCredentials = new SharePointOnlineCredentials(login, securePassword); string authCookieValue = onlineCredentials.GetAuthenticationCookie(_targetAdminSite); var cookieVal = authCookieValue.TrimStart("SPOIDCRL=".ToCharArray()); _userProfileService.CookieContainer = new CookieContainer(); _userProfileService.CookieContainer.Add(new Cookie( "FedAuth", cookieVal, String.Empty, _targetAdminSite.Authority)); } catch { return(false); } return(true); }
private static string GetCookies(string url, string account, string password) { try { if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(account) || string.IsNullOrWhiteSpace(password)) { return(null); } var securePassword = new SecureString(); foreach (var ch in password) { securePassword.AppendChar(ch); } var credentials = new SharePointOnlineCredentials(account, securePassword); return(credentials.GetAuthenticationCookie(new Uri(url))); } catch (Exception) { return(null); } }
private static async Task <byte[]> DownloadFile(Uri fileUri, SharePointOnlineCredentials credentials) { const string SPOIDCRL = "SPOIDCRL"; var authCookie = credentials.GetAuthenticationCookie(fileUri); var fedAuthString = authCookie.TrimStart($"{SPOIDCRL}=".ToCharArray()); var cookieContainer = new CookieContainer(); cookieContainer.Add(fileUri, new Cookie(SPOIDCRL, fedAuthString)); var securityHandler = new HttpClientHandler { Credentials = credentials, CookieContainer = cookieContainer }; using (var httpClient = new HttpClient(securityHandler)) { using (var request = new HttpRequestMessage(HttpMethod.Get, fileUri)) { var response = await httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsByteArrayAsync(); return(content); } } }
static void Main(string[] args) { string userName = "******"; string password = "******"; string apiUrl = "https://tenant.sharepoint.com/_api/search/query?querytext='docName'"; var securePassword = new SecureString(); foreach (char c in password.ToCharArray()) { securePassword.AppendChar(c); } var credential = new SharePointOnlineCredentials(userName, securePassword); Uri uri = new Uri(apiUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "GET"; request.Credentials = credential; request.Headers[HttpRequestHeader.Cookie] = credential.GetAuthenticationCookie(new Uri(apiUrl), true); // SPO requires cookie authentication request.Headers["X-FORMS_BASED_AUTH_ACCEPTED"] = "f"; HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse(); Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); }
public void SetAuthCookies() { Uri uri = new Uri(objSiteUrl); var authCookie = cred.GetAuthenticationCookie(uri); cookieContainer.SetCookies(uri, authCookie); }
public static string GetAccessTokenByUserInfo(Uri siteUrl, string userName, string password) { using (var secuePassword = GetPassword(password)) { var credential = new SharePointOnlineCredentials(userName, secuePassword); return(credential.GetAuthenticationCookie(siteUrl)); } }
public virtual string GetAuthenticationCookie([NotNull] Uri serverUri, [NotNull] NetworkCredential credential) { Assert.ArgumentNotNull(serverUri, "serverUri"); Assert.ArgumentNotNull(credential, "credential"); var credentials = new SharePointOnlineCredentials(credential.UserName, credential.SecurePassword); return(credentials.GetAuthenticationCookie(serverUri)); }
/// <summary> /// Upload a document /// </summary> /// <param name="webUrl"></param> /// <param name="loginName"></param> /// <param name="pwd"></param> /// <param name="document"></param> /// <param name="folderServerRelativeUrl"></param> /// <param name="fileName"></param> /// <returns></returns> public static async Task uploadDocumentAsync(string webUrl, string loginName, string pwd, System.IO.MemoryStream document, string folderServerRelativeUrl, string fileName) { try { //Creating credentials var passWord = new SecureString(); foreach (var c in pwd) { passWord.AppendChar(c); } SharePointOnlineCredentials credential = new SharePointOnlineCredentials(loginName, passWord); //Creating REST url const string RESTURL = "{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/add(url='{2}',overwrite=true)"; string rESTUrl = string.Format(RESTURL, webUrl, folderServerRelativeUrl, fileName); //Creating handler using (var handler = new HttpClientHandler() { Credentials = credential }) { //Getting authentication cookies Uri uri = new Uri(webUrl); handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri)); //Getting form digest var tFormDigest = GetFormDigest(handler, webUrl); tFormDigest.Wait(); //Creating HTTP Client using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Accept", "application/json;odata=nometadata"); client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true"); client.DefaultRequestHeaders.Add("X-RequestDigest", tFormDigest.Result.FormDigestValue); client.MaxResponseContentBufferSize = 2147483647; //Creating Content ByteArrayContent content = new ByteArrayContent(document.ToArray()); //Perform post HttpResponseMessage response = await client.PostAsync(rESTUrl, content).ConfigureAwait(false); //Ensure 200 (Ok) response.EnsureSuccessStatusCode(); } } } catch (Exception ex) { throw new ApplicationException($"Error uploading document {fileName} call on folder {folderServerRelativeUrl}. {ex.Message}", ex); } }
public static CookieContainer GetO365CookieContainer(SharePointOnlineCredentials credentials, string targetSiteUrl) { Uri targetSite = new Uri(targetSiteUrl); string cookieString = credentials.GetAuthenticationCookie(targetSite); CookieContainer container = new CookieContainer(); string trimmedCookie = cookieString.TrimStart("SPOIDCRL=".ToCharArray()); container.Add(new Cookie("FedAuth", trimmedCookie, string.Empty, targetSite.Authority)); return(container); }
/// <summary> /// Upload a document /// </summary> /// <param name="webUrl"></param> /// <param name="loginName"></param> /// <param name="pwd"></param> /// <param name="document"></param> /// <param name="folderServerRelativeUrl"></param> /// <param name="fileName"></param> /// <returns></returns> private static async Task ExecuteCall(string webUrl, string loginName, string pwd) { try { //Creating credentials var passWord = new SecureString(); foreach (var c in pwd) { passWord.AppendChar(c); } SharePointOnlineCredentials credential = new SharePointOnlineCredentials(loginName, passWord); //Creating REST url const string RESTURL = "{0}/_api/web/lists/GetByTitle('Stories')"; string rESTUrl = string.Format(RESTURL, webUrl); //Creating handler using (var handler = new HttpClientHandler() { Credentials = credential }) { //Getting authentication cookies Uri uri = new Uri(webUrl); string cookie = credential.GetAuthenticationCookie(uri); handler.CookieContainer.SetCookies(uri, cookie); //Getting form digest var tFormDigest = GetFormDigest(handler, webUrl); tFormDigest.Wait(); //Creating HTTP Client using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Accept", "application/json;odata=nometadata"); client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true"); client.DefaultRequestHeaders.Add("X-RequestDigest", tFormDigest.Result.FormDigestValue); client.MaxResponseContentBufferSize = 2147483647; HttpResponseMessage response = await client.GetAsync(rESTUrl).ConfigureAwait(false); string msg = await response.Content.ReadAsStringAsync(); //Ensure 200 (Ok) response.EnsureSuccessStatusCode(); } } } catch (Exception ex) { } }
public override void PreWebTest(object sender, PreWebTestEventArgs e) { using (ClientContext clientContext = new ClientContext(_siteUrl)) { Uri siteUri = new Uri(_siteUrl); string username = e.WebTest.UserName; string password = e.WebTest.Password; try { if (username.Contains("{{")) { //looks to be a databound field var usernamekey = e.WebTest.UserName.Replace("{{", "").Replace("}}", ""); username = (string)e.WebTest.Context[usernamekey]; } if (password.Contains("{{")) { //looks to be a databound field var passwordkey = e.WebTest.Password.Replace("{{", "").Replace("}}", ""); password = (string)e.WebTest.Context[passwordkey]; } } catch (Exception ex) { e.WebTest.Outcome = Outcome.Fail; e.WebTest.AddCommentToResult(ex.Message); } SecureString securePassword = new SecureString(); foreach (char c in password.ToCharArray()) { securePassword.AppendChar(c); } var credentials = new SharePointOnlineCredentials(username, securePassword); try { string authCookieValue = credentials.GetAuthenticationCookie(siteUri); authCookieValue = authCookieValue.Replace("SPOIDCRL=", ""); var cc = e.WebTest.Context.CookieContainer; cc.Add(new Cookie( "FedAuth", authCookieValue, String.Empty, siteUri.Authority)); Console.WriteLine(authCookieValue); } catch (IdcrlException ex) { e.WebTest.Outcome = Outcome.Fail; e.WebTest.AddCommentToResult(ex.Message); } } base.PreWebTest(sender, e); }
private bool AuthenticateUser(SharePointOnlineCredentials credentials, Uri urlToSite) { try { credentials.GetAuthenticationCookie(urlToSite); return(true); } catch (IdcrlException) { return(false); } }
static void Main(string[] args) { //Read from Project Online: all projects with their id and name. var odataEndpoint = _URL + "_api/ProjectData/"; var odataCommand = "Projects?$select=ProjectId,ProjectName"; //Get specific project //var odataCommand = $"Projects(guid'{_PROJECTGUID}')"; SecureString secpassword = new SecureString(); foreach (char c in _PASS.ToCharArray()) { secpassword.AppendChar(c); } var credentials = new SharePointOnlineCredentials(_USER, secpassword); var authCookieValue = credentials.GetAuthenticationCookie(new Uri(_URL)); ODataClientSettings settings = new ODataClientSettings() { BaseUri = new Uri(odataEndpoint), Credentials = credentials, IgnoreResourceNotFoundException = true, OnTrace = (x, y) => Console.WriteLine(string.Format(x, y)), PayloadFormat = ODataPayloadFormat.Json }; settings.OnApplyClientHandler = (System.Net.Http.HttpClientHandler clientHandler) => { //Deactivate cookie handling to be able to set my own one. clientHandler.UseCookies = false; }; settings.BeforeRequest = (System.Net.Http.HttpRequestMessage request) => { request.Headers.Add("Cookie", authCookieValue); }; var client = new ODataClient(settings); ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; var result = client.FindEntriesAsync(odataCommand).Result; var packages = result.ToList(); foreach (var package in packages) { Console.WriteLine(package["ProjectName"]); } Console.Read(); }
private Cookie GetFedAuthCookie(SharePointOnlineCredentials credentials) { string authCookie = credentials.GetAuthenticationCookie(new Uri(this.TenantUrl)); if (authCookie.Length > 0) { return new Cookie("SPOIDCRL", authCookie.TrimStart("SPOIDCRL=".ToCharArray()), String.Empty, new Uri(this.TenantUrl).Authority); } else { return null; } }
private Cookie GetFedAuthCookie(SharePointOnlineCredentials credentials) { string authCookie = credentials.GetAuthenticationCookie(new Uri(this.TenantAdminUrl)); if (authCookie.Length > 0) { return(new Cookie("SPOIDCRL", authCookie.TrimStart("SPOIDCRL=".ToCharArray()), String.Empty, new Uri(this.TenantAdminUrl).Authority)); } else { return(null); } }
/// <summary> /// No SPO client API for administering user profiles, so need to use traditional ASMX service for user profile work. This function initiates the /// web service end point, and authenticates using Office 365 auth ticket. Use SharePointOnlineCredentials to assist with this auth. /// </summary> /// <returns></returns> static bool InitializeWebService() { try { string webServiceExt = "_vti_bin/userprofileservice.asmx"; string adminWebServiceUrl = string.Empty; //append the web service (ASMX) url onto the admin web site URL if (_profileSiteUrl.EndsWith("/")) { adminWebServiceUrl = _profileSiteUrl + webServiceExt; } else { adminWebServiceUrl = _profileSiteUrl + "/" + webServiceExt; } LogMessage("Initializing SPO web service " + adminWebServiceUrl, LogLevel.Information); //get secure password from clear text password SecureString securePassword = GetSecurePassword(_sPoAuthPasword); //get credentials from SP Client API, used later to extract auth cookie, so can replay to web services SharePointOnlineCredentials onlineCred = new SharePointOnlineCredentials(_sPoAuthUserName, securePassword); // Get the authentication cookie by passing the url of the admin web site string authCookie = onlineCred.GetAuthenticationCookie(new Uri(_profileSiteUrl)); // Create a CookieContainer to authenticate against the web service CookieContainer authContainer = new CookieContainer(); // Put the authenticationCookie string in the container authContainer.SetCookies(new Uri(_profileSiteUrl), authCookie); // Setting up the user profile web service _userProfileService = new UPSvc.UserProfileService(); // assign the correct url to the admin profile web service _userProfileService.Url = adminWebServiceUrl; // Assign previously created auth container to admin profile web service _userProfileService.CookieContainer = authContainer; // LogMessage("Finished creating service object for SPO Web Service " + adminWebServiceUrl, LogLevel.Information); return(true); } catch (Exception ex) { LogMessage("Error initiating connection to profile web service in SPO " + ex.Message, LogLevel.Error); return(false); } }
/// <summary> /// Gets the authentication cookies. /// </summary> /// <param name="webUri">The web URI.</param> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <returns>CookieContainer.</returns> private static CookieContainer GetAuthCookies(Uri webUri, string userName, string password) { var securePassword = new SecureString(); foreach (var c in password) { securePassword.AppendChar(c); } var credentials = new SharePointOnlineCredentials(userName, securePassword); var authCookie = credentials.GetAuthenticationCookie(webUri); var cookieContainer = new CookieContainer(); cookieContainer.SetCookies(webUri, authCookie); return(cookieContainer); }
private bool ValidatePassword() { if (!ValidateUsername()) { errorMessage.Text = "Wrong User ID or Password, Please enter your Office 365 User ID and Password"; errorMessage.ForeColor = System.Drawing.Color.Red; errorMessage.Font = new Font("Microsoft Sans Serif", 10); return(false); } else { if (string.IsNullOrEmpty(txtPassword.Text)) { errorMessage.Text = "Wrong User ID or Password, Please enter your Office 365 User ID and Password"; errorMessage.ForeColor = System.Drawing.Color.Red; return(false); } else { try { System.Uri Office365URL = new Uri(ConfigurationManager.AppSettings["LoginURL"]); SecureString pass = new SecureString(); foreach (char c in txtPassword.Text) { pass.AppendChar(c); } SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(txtUserName.Text, pass); if (!string.IsNullOrEmpty(credentials.GetAuthenticationCookie(Office365URL))) { return(true); } else { errorMessage.Text = "Wrong User ID or Password, Please enter your Office 365 User ID and Password"; errorMessage.ForeColor = System.Drawing.Color.Red; return(false); } } catch (FormatException) { errorMessage.Text = "Wrong User ID or Password, Please enter your Office 365 User ID and Password"; errorMessage.ForeColor = System.Drawing.Color.Red; return(false); } } } }
private static CookieContainer GetAuthCookies() { var securePassword = new SecureString(); foreach (var c in onlinePassword) { securePassword.AppendChar(c); } var credentials = new SharePointOnlineCredentials(onlineUsername, securePassword); var authCookie = credentials.GetAuthenticationCookie(new Uri(defaultUrl)); var cookieContainer = new CookieContainer(); cookieContainer.SetCookies(new Uri(defaultUrl), authCookie); return(cookieContainer); }
public Auth(string rootSite, bool isSharepointOnline, string domain, string username, string password, string authScheme) { if (!isSharepointOnline) { NetworkCredential networkCredential; if (password == null && username != null) { Console.WriteLine("Please enter password for {0}", username); networkCredential = new NetworkCredential(username, GetPassword(), domain); } else if (username != null) { networkCredential = new NetworkCredential(username, password, domain); } else { networkCredential = CredentialCache.DefaultNetworkCredentials; } credentialsCache = new CredentialCache(); credentialsCache.Add(new Uri(rootSite), authScheme, networkCredential); CredentialCache credentialCache = new CredentialCache { { Util.getBaseUrlHost(rootSite), Util.getBaseUrlPort(rootSite), authScheme, networkCredential } }; httpHandler = new HttpClientHandler() { CookieContainer = new CookieContainer(), Credentials = credentialCache.GetCredential(Util.getBaseUrlHost(rootSite), Util.getBaseUrlPort(rootSite), authScheme) }; } else { SecureString securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } sharepointOnlineCredentials = new SharePointOnlineCredentials(username, securePassword); httpHandler = new HttpClientHandler(); Uri rootSiteUri = new Uri(Util.getBaseUrl(rootSite)); httpHandler.CookieContainer.SetCookies(rootSiteUri, sharepointOnlineCredentials.GetAuthenticationCookie(rootSiteUri)); } }
static void Main(string[] args) { bool checkPassed = CheckArguments(args); if (checkPassed == false) { ShowHelp(); return; } // As user for password and convert it into a secure string System.Security.SecureString mySecurePassword = GetSecurePassword(); // Getting the online credentials to work SharePointOnlineCredentials onlineCred = new SharePointOnlineCredentials(_username, mySecurePassword); // Get the cookie for authentication agains the web service string authCookie = null; try { authCookie = onlineCred.GetAuthenticationCookie(_adminUrl); } catch (Exception ex) { Console.WriteLine("\n" + ex.Message); return; } // Check if all worked well with the authentication if (authCookie != null) { Console.WriteLine("\nSuccessfully authenticated against Office 365 !!!"); Console.WriteLine("Begin updating user profiles"); // creating updater object UserProfileUpdater userProfUpdater = new UserProfileUpdater(authCookie, _adminUrl, _filename); // read update files and update profiles. userProfUpdater.Update(); } else { Console.WriteLine("Ups !!! Something went wrong but no exception was raised sorry"); } Console.WriteLine("WORK DONE !!!"); }
/// <summary> /// Used to modify the HTTP request based on authentication type /// </summary> /// <param name="request"></param> private void ModifyRequestBasedOnAuthPattern(HttpWebRequest request) { // Change the model based on used auth type switch (this.AuthType) { case AuthenticationType.DefaultCredentials: request.Credentials = CredentialCache.DefaultCredentials; break; case AuthenticationType.NetworkCredentials: NetworkCredential credential = new NetworkCredential(this.User, this.Password, this.Domain); CredentialCache credentialCache = new CredentialCache(); credentialCache.Add(new Uri(this.TargetSiteUrl), "NTLM", credential); request.Credentials = credentialCache; break; case AuthenticationType.Office365: // Convert password to secure string and create MSO Creds var spoPassword = new SecureString(); foreach (char c in this.Password) { spoPassword.AppendChar(c); } SharePointOnlineCredentials Credentials = new SharePointOnlineCredentials(this.User, spoPassword); Uri tenantUrlUri = new Uri(this.TargetSiteUrl); string authCookieValue = Credentials.GetAuthenticationCookie(tenantUrlUri); // Create fed auth Cookie and set that to http request properly to access Office365 site Cookie fedAuth = new Cookie() { Name = "FedAuth", Value = authCookieValue.TrimStart("SPOIDCRL=".ToCharArray()), Path = "/", Secure = true, HttpOnly = true, Domain = new Uri(this.TargetSiteUrl).Host }; // Hookup authentication cookie to request request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(fedAuth); break; default: break; } }
/// <summary> /// Download image thumbnail using Web URL /// This is mostly used with Apps /// </summary> /// <returns></returns> public byte[] DownloadThumbnail(string userName, string password, string relativeImageUrl) { if (!ClientContext.Web.IsObjectPropertyInstantiated("Url")) { ClientContext.Load(ClientContext.Web); ClientContext.ExecuteQuery(); } var url = string.Format("{0}/_layouts/15/getpreview.ashx?path={1}", ClientContext.Web.Url, relativeImageUrl); var securePassword = password.ToSecureString(); //Convert to format that Office365 will accept var credentials = new SharePointOnlineCredentials(userName, securePassword); var authCookie = credentials.GetAuthenticationCookie(new Uri(url)); WebClient client = new WebClient(); client.Headers.Add(HttpRequestHeader.Cookie, authCookie); var data = client.DownloadData(url); return(data); }
static private string GetSPOCookie() { // If successful, this variable contains an authentication cookie; // otherwise, an empty string. string result = String.Empty; try { // Construct a secure string from the provided password. // NOTE: For sample purposes only. var securePassword = new SecureString(); foreach (char c in spPassword) { securePassword.AppendChar(c); } // Instantiate a new SharePointOnlineCredentials object, using the // specified username and password. var spoCredential = new SharePointOnlineCredentials(spUsername, securePassword); // If successful, try to authenticate the credentials for the // specified site. if (spoCredential == null) { // Credentials could not be created. result = String.Empty; } else { // Credentials exist, so attempt to get the authentication cookie // from the specified site. result = spoCredential.GetAuthenticationCookie(new Uri(spSiteUrl)); } } catch (Exception ex) { // An exception occurred while either creating the credentials or // getting an authentication cookie from the specified site. Console.WriteLine(ex.ToString()); result = String.Empty; } // Return the result. return(result); }
/// <summary> /// Return the JSON result containing the web tiltle /// </summary> /// <param name="webUrl"></param> /// <returns></returns> private static async Task <string> getWebTitle(string webUrl) { //Creating Password const string PWD = "xxxx.1"; const string USER = "******"; const string RESTURL = "{0}/_api/web?$select=Title"; //Creating Credentials var passWord = new SecureString(); foreach (var c in PWD) { passWord.AppendChar(c); } var credential = new SharePointOnlineCredentials(USER, passWord); //Creating Handler to allows the client to use credentials and cookie using (var handler = new HttpClientHandler() { Credentials = credential }) { //Getting authentication cookies Uri uri = new Uri(webUrl); handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri)); //Invoking REST API using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false); response.EnsureSuccessStatusCode(); string jsonData = await response.Content.ReadAsStringAsync(); return(jsonData); } } }
//=============================================================================================== public static HttpClient GetClient(String webUrl, SharePointOnlineCredentials credential) { //Creating Handler to allow the client to use credentials and cookie var handler = new HttpClientHandler() { Credentials = credential }; //Getting authentication cookies Uri uri = new Uri(webUrl); handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri)); //Invoking REST API var client = new HttpClient(handler); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); return(client); }
private static void InvokeRestApiPost(Uri uri, SharePointOnlineCredentials credentials) { var authCookie = credentials.GetAuthenticationCookie(uri); string requestDigest = string.Empty; //POST: Request Digest using (HttpClientHandler handler = new HttpClientHandler()) { handler.CookieContainer.SetCookies(uri, authCookie); using (HttpClient client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.PostAsync($"{uri.AbsoluteUri}/_api/contextinfo", null).Result; dynamic json = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result); requestDigest = json.FormDigestValue; } } //POST: Delete File using (HttpClientHandler handler = new HttpClientHandler()) { handler.CookieContainer.SetCookies(uri, authCookie); using (HttpClient client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("X-RequestDigest", requestDigest); client.DefaultRequestHeaders.Add("X-HTTP-Method", "DELETE"); client.DefaultRequestHeaders.Add("IF-MATCH", "*"); var filePath = $"{uri.AbsolutePath}/shared documents/sample.docx"; var response = client.PostAsync($"{uri.AbsoluteUri}/_api/web/getfilebyserverrelativeurl('{filePath}')", null).Result; } } }
/// <summary> /// Executes the business logic /// </summary> /// <param name="logger">The logger.</param> public override void Run(BaseAction parentAction, DateTime CurrentTime, LogHelper logger) { if (parentAction != null) { this.Properties = parentAction.Properties; } CsvProcessor csvProcessor = new CsvProcessor(); string[] csvFiles = Directory.GetFiles(this.CSVDirectoryLocation, "*.csv", SearchOption.TopDirectoryOnly); logger.LogVerbose(string.Format("Attempting to get files from directory 'location' {0}. Number of files found {1}", this.CSVDirectoryLocation, csvFiles.Length)); foreach (string csvFile in csvFiles) { logger.LogVerbose(string.Format("Attempting to read CSV file '{0}' from location {1}", csvFile, this.CSVDirectoryLocation)); logger.LogVerbose(string.Format("Pausing the utility for '{0}' seconds so ASMX service is not overloaded", this.SleepPeriod)); Thread.Sleep(this.SleepPeriod * 1000); using (StreamReader reader = new StreamReader(csvFile)) { logger.LogVerbose(string.Format("Establishing connection with tenant at '{0}'", this.TenantSiteUrl)); using (ClientContext context = new ClientContext(this.TenantSiteUrl)) { Uri site = new Uri(this.TenantSiteUrl); try { UserProfileService.UserProfileService profileService = new UserProfileService.UserProfileService(site.ToString() + ProfileService); this.profileService = profileService; profileService.UseDefaultCredentials = false; using (SecureString password = new SecureString()) { foreach (char c in this.TenantAdminPassword.ToCharArray()) { password.AppendChar(c); } logger.LogVerbose(string.Format("Attempting to authenticate against tenant with user name '{1}'", this.TenantSiteUrl, this.TenantAdminUserName)); var crudentials = new SharePointOnlineCredentials(this.TenantAdminUserName, password); string cookie = crudentials.GetAuthenticationCookie(site); profileService.CookieContainer = new CookieContainer(); profileService.CookieContainer.Add(new Cookie(FedAuthCookieName, cookie.TrimStart(SPOIDCookieValue.ToCharArray()), string.Empty, site.Authority)); csvProcessor.Execute(reader, (entries, y) => { IterateCollection(context, entries, logger); }, logger); } } finally { if (this.profileService != null) { this.profileService.Dispose(); } } } } // Clean up current CSV file System.IO.File.Delete(csvFile); } }
/// <summary> /// No SPO client API for administering user profiles, so need to use traditional ASMX service for user profile work. This function initiates the /// web service end point, and authenticates using Office 365 auth ticket. Use SharePointOnlineCredentials to assist with this auth. /// </summary> /// <returns></returns> static bool InitializeWebService() { try { string webServiceExt = "_vti_bin/userprofileservice.asmx"; string adminWebServiceUrl = string.Empty; //append the web service (ASMX) url onto the admin web site URL if (_profileSiteUrl.EndsWith("/")) adminWebServiceUrl = _profileSiteUrl + webServiceExt; else adminWebServiceUrl = _profileSiteUrl + "/" + webServiceExt; LogMessage("Initializing SPO web service " + adminWebServiceUrl, LogLevel.Information); //get secure password from clear text password SecureString securePassword = GetSecurePassword(_sPoAuthPasword); //get credentials from SP Client API, used later to extract auth cookie, so can replay to web services SharePointOnlineCredentials onlineCred = new SharePointOnlineCredentials(_sPoAuthUserName, securePassword); // Get the authentication cookie by passing the url of the admin web site string authCookie = onlineCred.GetAuthenticationCookie(new Uri(_profileSiteUrl)); // Create a CookieContainer to authenticate against the web service CookieContainer authContainer = new CookieContainer(); // Put the authenticationCookie string in the container authContainer.SetCookies(new Uri(_profileSiteUrl), authCookie); // Setting up the user profile web service _userProfileService = new UPSvc.UserProfileService(); // assign the correct url to the admin profile web service _userProfileService.Url = adminWebServiceUrl; // Assign previously created auth container to admin profile web service _userProfileService.CookieContainer = authContainer; // LogMessage("Finished creating service object for SPO Web Service " + adminWebServiceUrl, LogLevel.Information); return true; } catch (Exception ex) { LogMessage("Error initiating connection to profile web service in SPO " + ex.Message, LogLevel.Error); return false; } }
/// <summary> /// Used to modify the HTTP request based on authentication type /// </summary> /// <param name="request"></param> private void ModifyRequestBasedOnAuthPattern(HttpWebRequest request) { // Change the model based on used auth type switch (AuthType) { case AuthenticationType.DefaultCredentials: request.Credentials = CredentialCache.DefaultCredentials; break; case AuthenticationType.NetworkCredentials: NetworkCredential credential = new NetworkCredential(User, Password, Domain); CredentialCache credentialCache = new CredentialCache(); credentialCache.Add(new Uri(TargetSiteUrl), "NTLM", credential); request.Credentials = credentialCache; break; case AuthenticationType.Office365: SharePointOnlineCredentials Credentials = new SharePointOnlineCredentials(User, this.Password); Uri tenantUrlUri = new Uri(TargetSiteUrl); string authCookieValue = Credentials.GetAuthenticationCookie(tenantUrlUri); // Create fed auth Cookie and set that to http request properly to access Office365 site Cookie fedAuth = new Cookie() { Name = "SPOIDCRL", Value = authCookieValue.TrimStart("SPOIDCRL=".ToCharArray()), Path = "/", Secure = true, HttpOnly = true, Domain = new Uri(TargetSiteUrl).Host }; // Hookup authentication cookie to request request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(fedAuth); break; default: break; } }
/// <summary> /// TODO: How to check authentication in on-prem scenarios? /// </summary> /// <param name="credentials"></param> /// <param name="urlToSite"></param> /// <returns></returns> private bool AuthenticateUser(SharePointOnlineCredentials credentials, Uri urlToSite) { try { credentials.GetAuthenticationCookie(urlToSite); return true; } catch (IdcrlException) { return false; } }
private ClientContext InitializeContext(string url, string userName, string password) { using (CommonHelper.LoggingScope) { using (var clientContext = new ClientContext(url)) { var sPassword = new SecureString(); foreach (char c in password.ToCharArray()) sPassword.AppendChar(c); var onlineCredentials = new SharePointOnlineCredentials(userName, sPassword); clientContext.Credentials = onlineCredentials; clientContext.ExecuteQuery(); var siteUri = new Uri(url); string authCookie = onlineCredentials.GetAuthenticationCookie(siteUri); GetCookieContainer = new CookieContainer(); string trimmedCookie = authCookie.TrimStart("SPOIDCRL=".ToCharArray()); GetCookieContainer.Add(new Cookie("FedAuth", trimmedCookie, string.Empty, siteUri.Authority)); return clientContext; } } }
public void InitializeContext() { AppEventLog.LogInfo("SharePointService InitializeContext start", ""); try { using (ctx = new ClientContext(SiteURL)) { var sPassword = new SecureString(); foreach (char c in Password.ToCharArray()) sPassword.AppendChar(c); var onlineCredentials = new SharePointOnlineCredentials(UserName, sPassword); ctx.Credentials = onlineCredentials; ctx.ExecuteQuery(); var siteUri = new Uri(SiteURL); string authCookie = onlineCredentials.GetAuthenticationCookie(siteUri); GetCookieContainer = new CookieContainer(); string trimmedCookie = authCookie.TrimStart("SPOIDCRL=".ToCharArray()); GetCookieContainer.Add(new Cookie("FedAuth", trimmedCookie, string.Empty, siteUri.Authority)); } } catch (Exception e) { string exp = e.Message + ((e.InnerException == null) ? "" : e.InnerException.Message); AppEventLog.LogInfo("SharePointService InitializeContext Error ", exp); } }
static void Main(string[] args) { ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true; FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete; FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest; FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse; FiddlerApplication.Startup(9898, FiddlerCoreStartupFlags.Default); try { ClientContext context = new ClientContext("https://victorvv.sharepoint.com"); SecureString se = new SecureString(); foreach (var cc in "1qaz2wsxE") { se.AppendChar(cc); } var cre = new SharePointOnlineCredentials("*****@*****.**", se); var cookie = cre.GetAuthenticationCookie(new Uri("https://victorvv.sharepoint.com")); } catch (Exception e) { } FiddlerApplication.Shutdown(); Console.ReadLine(); }