Authenticating client with office 365/SharePoint online - c#

I have a client application which consumes SharePoint web service (list.asmx). Recently SharePoint is migrated to SharePoint Online. Now authentication is failing.
This might be because authentication mechanism is different in SharePoint Online. I referred the article http://www.wictorwilen.se/Post/How-to-do-active-authentication-to-Office-365-and-SharePoint-Online.aspx for doing the authentication. However for some reason I am getting Authentication error now.
Please note I do not want authentication window to pop-up, as my client is a service.
Can anybody please give me some pointer/sample working application on how to do authentication with SharePoint Online?
Atul Sureka

SharePoint Online (SPO) uses claims-based authentication mode. Microsoft released SharePoint Online Client Components SDK which contains
SharePointOnlineCredentials class that could be utilized for SharePoint Web Services authentication in SPO.
How to authenticate SharePoint Web Services in SharePoint Online (SPO)
The following example demonstrates how to retrieve authentication cookies:
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;
}
Example
string sourceUrl = "https://contoso.sharepoint.com/Documents/SharePoint User Guide.docx";
string destinationUrl = "https://contoso.sharepoint.com/Documents/SharePoint User Guide 2013.docx";
FieldInformation[] fieldInfos;
CopyResult[] result;
byte[] fileContent;
using(var proxyCopy = new Copy())
{
proxyCopy.Url = webUri + "/_vti_bin/Copy.asmx";
proxyCopy.CookieContainer = GetAuthCookies(webUri, userName, password);
proxyCopy.GetItem(sourceUrl,out fieldInfos,out fileContent);
proxyCopy.CopyIntoItems(sourceUrl,new []{ destinationUrl}, fieldInfos, fileContent, out result);
}
References
Remote Authentication in SharePoint Online Using Claims-Based
Authentication
SharePoint Online Client Components SDK

You can use the SharePoint Client Object Model to login into SharePoint online. If you use the username and password for authentication, instead of OAuth method, there's no authentication window pops up.
As how to do it, please refer this article.

Related

Can't create SharePoint 2013 credentials in C# because username is not an email address

Our SharePoint 2013 is available without logging in because we are logged in to Windows and the Windows credentials are passed to SharePoint.
I am creating a C# app to read lists of files in a Documents site on SharePoint and download some of them. But I've fallen at the first step. I can't create SharePoint credentials that SharePoint will accept, because the username is not an email address and SharePointOnlineCredentials will not accept a username that is not an email address. This is my current code:
using (ClientContext clientContext = new ClientContext(UriString))
{
clientContext.Credentials = new SharePointOnlineCredentials(UserName, Password);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
Console.WriteLine(web.Title);
}
I have tried collecting the Network credentials,
var credentials2 =new NetworkCredential(UserName, Password, "MyDomain");
but I can't convert/cast the Network credentials into SharePoint credentials.
How can I connect to SharePoint and experience the same rights that I have through Windows? (with the same username and password)
If I understand correctly, you are using a SharePoint 2013 on premise environment (using windows authentication)?
For default windows authentication use DefaultNetworkCredential instead of SharePointOnlineCredentials

Sharepoint 2010 User Authentication (windows Credential) with Client Object Model

I am trying to login to a SharePoint website that uses Windows Integrated (NTLM) authentication. There are 2 ways to enter credentials for the SharePoint website, Windows Authentication and form authentication.
However, Form authentication is disable on this specific website and I can only use windows authentication. Is there a way for me to login to this site with different credential than what I used to login to my windows machine?
See error here: Form authentication denied
String site = "http://sharepoint/";
ClientContext context = new ClientContext(site);
context.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
FormsAuthenticationLoginInfo formsAuthInfo = new FormsAuthenticationLoginInfo("MyUser", "MyPassword");
context.FormsAuthenticationLoginInfo = formsAuthInfo;
// The SharePoint web at the URL.
Web web = context.Web;
// We want to retrieve the web's properties.
context.Load(web);
// Execute the query to the server.
context.ExecuteQuery();
InitializeComponent();
I also tried to use:
context.Credentials = new NetworkCredential("user", "pass", site);
ClientContext context = new ClientContext(site);
context.Credentials = new NetworkCredential("user", "pass", site);
// The SharePoint web at the URL.
Web web = context.Web;
// We want to retrieve the web's properties.
context.Load(web);
// Execute the query to the server.
context.ExecuteQuery();
InitializeComponent();
I get the following 401 (unauthorized) error
Instead of changing the ClientContext object's AuthenticationMode property to FormsAuthentication, try setting the object's Credentials property to a valid Network Credential object.
ClientContext context = new ClientContext("http://sharepointsite/");
context.Credentials = new NetworkCredential("username","password","domain");
Don't know if it is late but, by default, the managed client object models authenticate users by using their Windows credentials (DefaultCredentials).
So you don't need to explicitly set the Credentials. Just Set following -
context.AuthenticationMode = ClientAuthenticationMode.Default;

Unable to connect to my Tfs server from c# code

We're trying to authenticate to our hosted TFS service account in c# using TeamFoundationServer .net control, here is my code :
NetworkCredential tfsCredential = new NetworkCredential(username, password);
TeamFoundationServer tfsServer = new TeamFoundationServer(tfsAddress, tfsCredential);
tfsServer.Authenticate();
Note that this is not an on-premises TFS server, it is the hosted TFS service at tfspreview.com and we try to sign-in with windows live account and with alternate authentication credentials but every time we try to authenticate, internet explorer open in a new windows and ask for credentials.
If we use the IE prompt to connect it works but we want to store the credentials and connect to the server without asking for the credentials every time,
You can either configure basic authentication under your profile or you can use a service credential. It all depends on what sort of permission you need. The basic auth operates under a user account which tends to be bad practice while the service account had elevated permissions.
Configure basic authentication for TF Service
For basic user authentication you should connect to TF Service and open your profile as indicated. There is a "Credentials" tab on your profile which will let you configure those credentials. This is good for per/user access through the API but is not good if you want to run things through a server or service.
Retrieve TFS Service Credentials
I created an application called the TFS Service Credential Viewer that allows you to retrieve the service credentials for your TF Service instance. This is the same thing that the Build & Test servers do when you configure them locally to work against the cloud.
I hope this helps...
You can try with this code based on impersonation of server
var serverUrl = "";
ICredentials credentials = new NetworkCredential(username, password, domain);
ICredentialsProvider TFSProxyCredentials = new NetworkCredentialsProvider(credentials);
TfsTeamProjectCollection currentCollection = new TfsTeamProjectCollection(new Uri(serverUrl), credentials);
// Get the TFS Identity Management Service
IIdentityManagementService identityManagementService = currentCollection.GetService<IIdentityManagementService>();
// Look up the user that we want to impersonate
TeamFoundationIdentity identity = identityManagementService.ReadIdentity(IdentitySearchFactor.AccountName, username, MembershipQuery.None, ReadIdentityOptions.None);
// Open collection impersonated
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(serverUrl), credentials, TFSProxyCredentials, identity.Descriptor);
//For example we can access to service WorkItemStore
var workItemStore = tfs.GetService<WorkItemStore>();
Tfspreview.com now supports basic authentication which would eliminate IE being displayed at all. See here for details on how to set this up for your tfspreview.com and then use the username and password you configured.

YouTube and OAuth 2.0 in .Net

Does anyone know how to properly authenticate an account using OAuth 2.0 and then use that auth token to access the user's YouTube account?
At the end of http://code.google.com/apis/youtube/2.0/developers_guide_protocol_oauth2.html it says
The Google Data client libraries that support the YouTube Data API do not currently support OAuth 2.0. However, a newer set of Google API client libraries, which do not support the YouTube Data API, do provide OAuth 2.0 support.
As such, it is an option to use these newer libraries, which are listed below, for their OAuth 2.0 capabilities and then force the Google Data client library to use the OAuth 2.0 token(s) that you have obtained.
I have my application successfully running through the OAuth 2.0 process and I'm getting an access token which should be able to access youtube, but I don't know how to "force the Google Data client library to use the OAuth 2.0 token(s)".
Any example code would be great.
Liron
PS This is for a desktop application.
Do do this you need to have both an account set up on google data apps (https://code.google.com/apis/console) and with the youtube apis (http://code.google.com/apis/youtube/dashboard).
You then have to authenticate the google data api using their oauth mechanisms. Something like the following - this is gutted from some code we have.
{code}
//Create Client
m_Client = new NativeApplicationClient(GoogleAuthenticationServer.Description, m_ClientID, m_ClientSecret);
//Add Youtube scope to requested scopes
m_Scopes.Add("https://gdata.youtube.com");
//Get Authentication URL
authStateInitial = new AuthorizationState(m_Scopes);
authStateInitial.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = m_Client.RequestUserAuthorization(authStateInitial);
//Navigate to URL, authenticate get accessToken
string accessToken = ...;
string[] tokens = accessToken.Split(new char[] { '&' });
if(tokens.Length == 2)
{
authStateFinal = new AuthorizationState(m_Scopes);
authStateFinal.AccessToken = tokens[0];
authStateFinal.RefreshToken = tokens[1];
if(m_AuthStateInitial == null)
{
m_Client.RefreshToken(m_AuthStateFinal);
}
OAuth2Authenticator<NativeApplicationClient> authenticator = new OAuth2Authenticator<NativeApplicationClient>(m_Client, GetState); //GetState returns authStateInitial
authenticator.LoadAccessToken();
}
Then you have to authenticate the youtube apis by using both the access token you got from above and the youtube Developer Key.
{code}
GAuthSubRequestFactory m_Authenticator = new GAuthSubRequestFactory(ServiceNames.YouTube, "Product Name");
m_Authenticator.Token = AccessToken;
YouTubeService m_YouTubeService = new YouTubeService(m_Authenticator.ApplicationName, m_DeveloperKey);
m_YouTubeService.RequestFactory = m_Authenticator;
Hope this helps someone.

Interacting with google appengine from C#

I'm writing a google appengine application, which stores data and has a web front end. I want to be ableto pull down this data in a C# program. This means I need to authenticate with the site (users must be logged in to view the data). How can I authenticate like this? I tried setting credentials on the WebClient but I keep getting the google login page.
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
//should it be username#gmail.com ??
client.BaseAddress = "http://nosoperor-internal.appspot.com";
String s = client.DownloadString("/bank");
//s now contains the google login page, unfortunately
I found an answer in this blog:
Accessing authenticated Google App Engine services from a .NET CF client
and it works ^^
AFAIK, you need to probably use Google Data protocols and account APIs to authenticate.
Edit: I would download the .Net client library and try the examples in there. This is a copy paste from the docs:
Service service = new Service("cl", "exampleCo-exampleApp-1"));
// Set your credentials:
service.setUserCredentials("jo#gmail.com", "mypassword");

Categories

Resources