This post is migrated from previous hosting provider. There are still some issues with old posts. Please make a comment on this post with any issues.

How to do active authentication to Office 365 and SharePoint Online

Tags: SharePoint 2010, Office 365

This is a post detailing how you perform active authentication to SharePoint Online in Office 365. Active authentication is required when you need to authenticate in code to programmatically access SharePoint objects, using for instance Client Object Model, web services or WebDAV from outside of Office 365. When you are "in" SharePoint Online or using the web browser this is not needed since you are either already authenticated and the web browser handles the authentication using active authentication.

Note: The active authentication "mechanism" have unfortunately changed a few times the last month without any notice. I had a really bad timing with one of these changes just a couple of days before demoing it on TechDays here in Sweden. With that said - I cannot guarantee that this method will work in the future. But if it changes I'll try to update the post or write a new one...

SharePoint Online active AuthN basics

Before digging into the actual code I think it is important to understand how it actually works and what the code does. This is easier done using a diagram.

Passive claims AuthN

What happens is that we need to request a token from the STS. In Office 365 the STS is located at https://login.microsoftonline.com/extSTS.srf. To request the token from the STS we pass the username and password using the SAML 1.1 protocol. If the authentication is successful the STS returns a security token. This security token is sent to SharePoint and if SharePoint successfully validates the token it will return two cookies (called FedAuth and rtFa). These two tokens must then be passed along with all requests to SharePoint.

There are some other interesting things happening here  that you need to be aware of. For instance; you need to be aware of which Office 365 subscription you are targeting. P-subscriptions must use HTTP Url's when communicating and E-subscriptions must use HTTPS. Using HTTPS for P-subscriptions will create redirect responses that eventually will drive you crazy when trying to code around them (I got a solution for that though - but I can't get any worse anyways).

How to use Client Object Model with Office 365 from a remote client

To be able to remotely invoke methods on SharePoint Online using Client Object Model (CSOM), web services or WebDAV we need to authenticate first, according to above. Then we need to pass along the cookies for each request. And this is how we do it. Once you have the cookies (FedAuth and rtFA) you need to create a CookieContainer object in which you add the cookies. This CookieContainer must then be added to the request done by the Client Object Model before the request is done. The client runtime Context object has an event called ExecutingWebRequest that can be used for this. The code could look something like this:

context.ExecutingWebRequest += (s,e) => {
    e.WebRequestExecutor.WebRequest.CookieContainer = 
        createCookieContainer();
    e.WebRequestExecutor.WebRequest.UserAgent = userAgent;
};

The createCookieContainer() method is the one responsible for creating the cookie container, more on this one later. Also note here that I set the UserAgent of the request to a new value. This is important! If you do not set any user agent of this request SharePoint Online will gently throw a 403 Forbidden error if you're on an E-subscription. It works fine without on P-subscriptions, but it doesn't harm to add it. So just do it all the time, for the sake of it! The user agent could be any normal browser - this is what I use:

"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)" 

That's basically it! Use the same procedure when you're manually using WebRequest objects or when you're using the SharePoint web services. Just add the cookies and user agent and you're fine.

Show me the code to get the cookies!

Now to the core of this article. How does the code look like to get the actual cookies? As a good TV-chef I've prepared all the things you need to make it really easy for you. I've been using a number of helper classes for a couple of months now and first showed them during TechDays 2011. Chris Johnson, Microsoft, also made a version of them for his blog post on the topic. My helper class has an origin in posts from Steve "SharePoint Claims" Peschka. I've modified and tweaked his code samples so that they work with SharePoint Online.

What I've done is a helper class called MsOnlineClaimsHelper. This class contains all you need to authenticate, retrieve and cache the cookies and piggyback the cookie container on the CSOM web requests. Let's see a very simple sample:

MsOnlineClaimsHelper claimsHelper = new MsOnlineClaimsHelper(url, username, password);

using (ClientContext context = new ClientContext(url)) {

    context.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;

    context.Load(context.Web);
                
    context.ExecuteQuery();

    Console.WriteLine("Name of the web is: " + context.Web.Title);
                
}

On the first line I create the helper object and pass in the URL, username and password. This class will once used do the active authentication for you and cache the cookies until they expire. It will handle the HTTP/HTTPS problem with the E/P-subscriptions mentioned earlier, the User Agent problem and everything else you need. Yes, you will be able to download the code later. After creating the client context I hook up a helper method of the MsOnlineClaimsHelper class called clientContext_ExecutingWebRequest. This method is the one adding the cookies and fixing the user agent. Then it's just to use the client object model as usual. Remember that when you are using P-subscriptions the URL's passed into the client object model must be HTTP (the helper class doesn't really care and can handle both) and use HTTPS for E-subscriptions.

The helper class is made so that you can reuse it, so you don't have to re-authenticate all the time, since that will really slow your application down. If you need the CookieContainer to add to your own web requests it has a property called (surpise!) CookieContainer that you can use.

To illustrate another use, that also is a very useful helper class, is a Office 365 claims aware WebClient derivative.

public class ClaimsWebClient : WebClient {
    private readonly MsOnlineClaimsHelper claimsHelper;

    public ClaimsWebClient(Uri host, string username, string password) {
        claimsHelper = new MsOnlineClaimsHelper(host, username, password);
    }
    protected override WebRequest GetWebRequest(Uri address) {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest) {
            (request as HttpWebRequest).CookieContainer = claimsHelper.CookieContainer;
        }
        return request;
    }
}

This is a class that can be used just as the normal WebClient class. Using this one you enable WebDAV fiddling with SharePoint Online. It's very useful to upload and retrieve documents using PUT and GET methods.

The download

I promised you to see the code how we actually retrieves the cookies. Sorry, I won't. I'll leave that to you. Download the code sample, including all helper classes, by clicking this link and experiment with it as you like.

Happy coding!

Updated: Sometimes you're tired - mixed up passive and active...

93 Comments

  • Phill Duffy said

    Hi Wictor, been pulling my hair out for a couple of days on Chris Johnsons code for this, I am glad you have got this update code out there and I have tested it successfully! Thanks again Phill

  • Wictor said

    Yea, CJ's code worked perfectly just a couple of days ago :). But this is the nature of a beta. And as I wrote in the post, they have changed it a couple of times already so I guess they have more changes in the pipe.

  • mincho said

    Hi Wictor, great job! Could you provide a sample how to access SP-Online via web-service. CSOM works perfectly.

  • Arthur said

    Thanks Wictor, the UserAgent trick solved my problem. But Office 365 seems to be rejecting HTTP PUT method when I am using Microsoft.SharePoint.Client.File.SaveBinaryDirect() to create a new file on 'Shared Documents'. Do you have any idea why this is happening? Or any other suggestion to perform the same task? Thank you.

  • Wictor said

    Haven't tried SaveBinaryDirect. I have used the ClaimsWebClient (included in the sample) with the PUT method to upload stuff into SPOL.

  • Arthur said

    Thanks again, I got it to work with my own HTTP request. SaveBinaryDirect() fires ExecutingWebRequest event after the request stream is flushed and closed. By then it is too late to add the cookies to the request. Cheers :)

  • Chris said

    Thanks, but any idea as to how I can have it working on Windows XP as it does not support Microsoft.IdentityModel.dll and specifically the WSTrustChannel.

  • Ashish said

    Hi, I would like to authenticate user for 365 using webservices in my window application. Can you please provide comments how can I achieve this things? Thanks, Ashish Chotalia

  • Wictor said

    Since the WIF isn't supported on XP I think your only option is to use Reflector and build the stuff yourself. It's essentially HTTP and encryption.

  • Jamie said

    Hi, When I try your code (and CJs), I get the error Microsoft.SharePoint.Client.ClientRequestException: Cannot contact site at the specified URL https://thickshake.sharepoint.com/ I'm incredibly lost here. I can access the site in my browser, do I need to allow certain permissions for this to happen?

  • Christine said

    Any suggestions on how to get the token for a SharePoint Online site using SSO through Active directory synchronization? Thanks!

  • Ronak said

    I tried to add service reference to ExcelService.asmx but the proxy created does not work with SharePoint online.

  • Berend Engelbrecht said

    Hi, I am trying to programmatically access files on office 365 sharepoint server. Your article helped me a long way: authentication works fine and I can download files without problems. But Client.File.SaveBinaryDirect gives me 405 "method not allowed". It would be great if you could explain how to upload. Thank you!

  • Kaustubh said

    Hi, Thanks for this awesome code, however am gatting the following error when trying to run your code through a console application: An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail. InnerException: Authentication Failure This happens on the following method: public Message EndIssue(IAsyncResult asyncResult) under public partial class WSTrustFeb2005ContractClient : ClientBase<iwstrustfeb2005contract>, IWSTrustFeb2005Contract in WcfClientContracts.cs. Could you please suggest what might be causing this and suggest a solution? I've confirmed that the credentials I pass are correct. I'm trying to hit the following url: https://microsoft.sharepoint.com/sites/LCA/iea5ppe</iwstrustfeb2005contract>

  • SEvans said

    Great piece of code Wichtor. As others have noted, SaveBinaryDirect does not work correctly, as the FedAuth cookies never get attached to the HTTP PUT request that the method generates. Here's my workaround - hope this helps some of you: // "url" is the full destination path (including filename, i.e. https://mysite.sharepoint.com/Documents/Test.txt) // "cookie" is the CookieContainer generated from Wichtor's code // "data" is the byte array containing the files contents (used a FileStream to load) System.Net.ServicePointManager.Expect100Continue = false; HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.Method = "PUT"; request.Accept = "*/*"; request.ContentType = "multipart/form-data; charset=utf-8"; request.CookieContainer = cookie; request.AllowAutoRedirect = false; request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; request.Headers.Add("Accept-Language", "en-us"); request.Headers.Add("Translate", "F"); request.Headers.Add("Cache-Control", "no-cache"); request.ContentLength = data.Length; using (Stream req = request.GetRequestStream()) { req.Write(data, 0, data.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream res = response.GetResponseStream(); StreamReader rdr = new StreamReader(res); string rawResponse = rdr.ReadToEnd();

  • SEvans said

    Great piece of code Wichtor. As others have noted, SaveBinaryDirect does not work correctly, as the FedAuth cookies never get attached to the HTTP PUT request that the method generates. Here's my workaround - hope this helps some of you: // "url" is the full destination path (including filename, i.e. https://mysite.sharepoint.com/Documents/Test.txt) // "cookie" is the CookieContainer generated from Wichtor's code // "data" is the byte array containing the files contents (used a FileStream to load) System.Net.ServicePointManager.Expect100Continue = false; HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.Method = "PUT"; request.Accept = "*/*"; request.ContentType = "multipart/form-data; charset=utf-8"; request.CookieContainer = cookie; request.AllowAutoRedirect = false; request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; request.Headers.Add("Accept-Language", "en-us"); request.Headers.Add("Translate", "F"); request.Headers.Add("Cache-Control", "no-cache"); request.ContentLength = data.Length; using (Stream req = request.GetRequestStream()) { req.Write(data, 0, data.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream res = response.GetResponseStream(); StreamReader rdr = new StreamReader(res); string rawResponse = rdr.ReadToEnd();

  • SEvans said

    Great piece of code Wichtor. As others have noted, SaveBinaryDirect does not work correctly, as the FedAuth cookies never get attached to the HTTP PUT request that the method generates. Here's my workaround - hope this helps some of you: // "url" is the full destination path (including filename, i.e. https://mysite.sharepoint.com/Documents/Test.txt) // "cookie" is the CookieContainer generated from Wichtor's code // "data" is the byte array containing the files contents (used a FileStream to load) System.Net.ServicePointManager.Expect100Continue = false; HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.Method = "PUT"; request.Accept = "*/*"; request.ContentType = "multipart/form-data; charset=utf-8"; request.CookieContainer = cookie; request.AllowAutoRedirect = false; request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; request.Headers.Add("Accept-Language", "en-us"); request.Headers.Add("Translate", "F"); request.Headers.Add("Cache-Control", "no-cache"); request.ContentLength = data.Length; using (Stream req = request.GetRequestStream()) { req.Write(data, 0, data.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream res = response.GetResponseStream(); StreamReader rdr = new StreamReader(res); string rawResponse = rdr.ReadToEnd();

  • Dave said

    When using P1 plan and set SharePoint public web site to use custom site such as "www.company.com", the team site url changed too. This will break the authentication using the code described here.

  • Henning Groß said

    Hi! I am using your classes without modifications and with credits to this site in this open source project: https://evolvis.org/projects/dmsapi/ I hope this is OK but had a hard time figuring what the license on your code is. Please contact me if you dont like your code to be included and I will write my own implementation removing yours. I will spend a few more working days on implementing features and tests and would love to have more committers to make this api even more powerful. Anyone who wants their application to be able to communicate with different versions of sharepoint or other DMS-Systems even feel free to use/improve it.

  • Henning Groß said

    Hi! I am getting: WebException: The underlying connection was closed from time to time. Any idea what could cause that? Id appreciate a solution :)

  • Henning said

    Hi! If anyone experiences the same problems. It seems like this fixes it: protected override WebRequest GetWebRequest(Uri address) { ... (request as HttpWebRequest).KeepAlive = true; ... } AND public void clientContext_ExecutingWebRequest(object sender, WebRequestEventArgs e) { ... e.WebRequestExecutor.RequestKeepAlive = true; } I dunno if both are nessecary.

  • Niclas Pålsson said

    I got a call from one of our contacts at Microsoft, they asked if we support Office SharePoint 365 in our Document Management system (DS2011) for Dynamics CRM. It didn't work out of the box but after reading your post we solved the authentication issues and can now add Office SharePoint 365 to the list of SharePoint scenarios supported, and this just a few days after Microsoft released the support for integration between Office 365 and CRM online. Sweet! Thanks for a great post!

  • Thomas Jorgensen said

    Wonderfully helpful - at least as long as you stay clear of federated users. Unfortunately, I presently need to authenticate against an Office365 with federation service enabled, and that stops this otherwise great solution short. Using the Gui, once the user name has been entered, the user is asked to login to 'fed<customer domain="">'. As long as I am using the GUI, this works fine. Using your code, I run into the following exception: Object reference not set to an instance of an object. Stack trace: at Wictor.Office365.MsOnlineClaimsHelper.getCookieContainer() in D:\Projects\A2\MigrateTool\Wictor.Office365.ClaimsDemo\MsOnlineClaimsHelper.cs:line 79 at Wictor.Office365.MsOnlineClaimsHelper.get_CookieContainer() in D:\Projects\A2\MigrateTool\Wictor.Office365.ClaimsDemo\MsOnlineClaimsHelper.cs:line 118 ... I have debugged the exception to the following lines - specifically it occurs in the EndIssue method: Message response = trustClient.EndIssue( trustClient.BeginIssue( Message.CreateMessage( MessageVersion.Default, WSTrustFeb2005Constants.Actions.Issue, new RequestBodyWriter(trustSerializer, rst) ), null, null)); Any idea how to fix this? I have been searching far and wide for code to authenticate against federated users in Office365, but so far without luck. </customer>

  • Kirk Liemohn said

    I am getting a connection failure. This blog is over 7 months old, so I'm wondering if things have changed since then or if the problem is more on my end. I get the following error with no additional information (no inner exception) when I do context.ExecuteQuery(): Cannot contact site at the specified URL http://threewill.sharepoint.com/sites/kirk. I haven't dug in too far yet, but I thought I would post this before spending too much time in case I'm not the only one.

  • Rodion said

    I think the code is over-complicated in a part where you get the token from STS. If you are using the WIF then there is alredy a UserNameWSTrustBinding and WsTrustChannel implemented. I'm not sure if I can post the code here but it is half of the size and no need for serialization / XML tricks. Apart from that as it was already mentioned in several comments above, it would be geat to see the way to authenticate using SSO credentials. It looks like extSTS.srf does not accept tokens issued by trusted federated authority. At least using standard WsTrust methods. Any suggestions? (apart from using passive federation via login.sfr)

  • Dan said

    This is a great post. Through a Silverlight client running in a WebPart, I am already authenticated on SPO through the browser and I'd rather not prompt the user for a username/password in order to get the token. Through Silverlight's client HTTP stack, there is support for cookies but I can't just grab the one that is in the browser (I don't think), and I can't use the browser HTTP stack because I need to do a "PUT" in order to stream up a large file. Can you think of a solution?

  • al said

    Thank you for your post. Can I use this approach to authenticate against the team site? like by redirecting along with passing the cookies to the www.yoursite.sharepoint.com ?

  • Sagar said

    Thank you for your post. I want to know, what will be url for trial version of office365. currently i m providing it as "https://mydomainname.onmicrosoft.sharepoint.com" but it not returning cookies. i have provided right credential. trail plan is E3. thats why i have use https instead of http. help me.

  • TheGrimAce said

    I tried the code, but when I get the SAML token from the site in getSamlToken(), I don't have a BynarySecurityToken in it. Any ideas what could be the problem?

  • TheGrimAce said

    I tried the code, but when I get the SAML token from the site in getSamlToken(), I don't have a BynarySecurityToken in it. Any ideas what could be the problem?

  • Raj PArmar said

    Thomas Jorgensen has mentioned issue with EndIssue call..I am also getting same error.Any help? Thx. CALL >> return base.Channel.EndIssue(asyncResult);

  • Wictor said

    @Tim,
    while that example works it is not that efficient since it relies on using the Windows Forms WebBrowser client class, which doesn't work in high-perf scenarios or on all platforms.
    /WW

  • volfar said

    Hello!
    This code does not work with office 365 that migrated BPOS site.
    Token does not have BinarySecurityToken.
    See this question:
    http://sharepoint.stackexchange.com/questions/31144/claims-based-auth-failing-for-a-migrated-bpos-site/39221#39221
    Please help to autentificate to portal that migrated from bpos site.

  • John Guilbert said

    Fair play to you Wictor,
    The Problem I am having sounds very similar to other users. I have tested your code in a console App and Dugging on a Web Service. However, when I deploy the web service that has your code in it it comes up with the following error:

    Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
    at Wictor.Office365.MsOnlineClaimsHelper.getCookieContainer()
    at Wictor.Office365.MsOnlineClaimsHelper.clientContext_ExecutingWebRequest(Object sender, WebRequestEventArgs e)
    at Microsoft.SharePoint.Client.ClientRuntimeContext.OnExecutingWebRequest(WebRequestEventArgs args)
    at Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()
    at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
    at Wictor.Office365.ClaimsDemo.Program.Main(String[] args)

    I am guessing the container is blank.BUT WHY! If someone could tell me how I can get around this OR why it would do this in this code. Please let me know....this is driving me nuts!

  • Jens Willmer said

    Thanks for this article it helped me alot!
    Have you tried to login via an Active Directory Federation Services (ADFS) to Office365? I have to manage this for a project but with the redirect to this service your code doesent work.
    If I succeed I will tell you, that could improve your article ;-)

    Jens

  • Raul Lopez said

    Hi Wictor.

    Thanks for your code. Work fine for me in windows form app.

    Now I try to run in a Metro style app (Framework 4.5) but not found in this framework (System.web.dll problems...).

    I am trying to update your code but do you have the code with framework 4.5? or do you think if that is possible?

    Saludos.

    Thanks.

  • Anup Baldawa said

    Hello,

    Thank you for the code, I am trying to use your code and upload a document to Sharepoint Online (365) using HTTP Put.

    Is it possible to have some code reference on how to achieve it. I am new to Sharepoint and .Net framework. Do not have a lot of understanding on how it works.

    Thank you for the help.

  • Anna Jhaveri said

    Thank you for the code, i am trying to use you code but sometimes when connecting to office 365 site i am getting this error "the communication object system.servicemodel.channels.servicechannel cannot be used for communication because it is in the faulted state" on line "return base.Channel.EndIssue(asyncResult);". Has someone already faced this issue, what can be the cause of this error?

    Thanks,
    Anna

  • Jens Willmer said

    Referred to my last comment (http://www.wictorwilen.se/Post/How-to-do-active-authentication-to-Office-365-and-SharePoint-Online.aspx#comment-5690) about establishing a connection through an ADFS you will find the answer at stackoverflow (http://stackoverflow.com/questions/11295953/claim-auth-from-adfs/11651778#11651778) or detailed at my blog (http://jwillmer.de) as soon as the poc is done.
    Hope that this additional infos can help some of your readers ;-)

    Jens Willmer

  • Martin Harris said

    Thanks for the information and code Wictor, this has been tremendously useful for our project.

    I just tested this out in a Wave 15 Preview SharePoint Online tenancy and it worked perfectly!

    http://sharepointrepairjoint.blogspot.com.au/2012/07/sharepoint-online-2013-preview.html

  • Vishal said

    Hi wictor
    great work your solution works fine for me but after sometime it generate error. I check my sharepoint online site when i login it display me this page http://screencast.com/t/II2ussu7CC6a so there is a problem in authentication because of this?

  • Shashi said

    Wonderful !!! . This is what I have been searching. Big plus is that do not have to login again and sending the passwords again and again (security risk). Performance is another plus comes handy because of helper class… Thanks you

  • plan p1 said

    Hi Wictor
    Awesome work

    Code works fine for E plans(i.e htts urls)

    When i am using code for authencate against plan p1, response gives me object reference error and i am not able to connect.
    Can you please provide some work around ?

  • plan p1 said

    Continue with above discussion point

    Eg . Code works and authencates for url like https://abc.sharepoint.com(E plans)
    but does not work or authencate url like http://abc.sharepoint.com
    or http://abc.sharepoint.com/teamsite (P plans)

    Please provide me some way.

  • plan p1 said

    Hi Wictor

    Is there any updates regarding my problem ?
    I have posted a issue on 8-Nov with same name.
    Please help me on this..

  • David L. Bojsen said

    Hi

    Thank you for your great Work.

    I am trying to change the MsOnlineClaimsHelper to Work for logging in with a live.dk email address. This address has been gived guest rights to my SharePoint online site, and can login via web.
    I have tried changing these two lines:
    public const string office365STS = "https://login.live.com/extSTS.srf"; //"https://login.microsoftonline.com/extSTS.srf";
    public const string office365Login = "https://login.live.com/login.srf"; //"https://login.microsoftonline.com/login.srf";
    But this doesn't Work.

    Can you help me, please ?

    Best regard

    David

  • Jomit said

    Excellent article !! It helped me a lot in understanding the authentication flow of SharePoint Online.

    I wasn't able to get the “MsOnlineClaimsHelper” to work as it kept throwing errors while fetching the response using ‘WSTrustFeb2005ContractClient’ but I managed to use a different approach to make it work. I have mentioned all the details on my blog ( http://jomit.blogspot.com/2012/12/authentication-with-office-365-from-on.html )

    Thanks,
    Jomit

  • John Guilbert said

    Hi Wictor,

    It's a shame, but we had this working fine until we moved to a federated connection (Actiove Directory synced). There is an additional site that is accessed during authetication. This link is a microsoft site "nexus".
    Anyways, if you have a fix, can you drop me a line.
    Thanks.
    John.

  • sreenivasulu said

    hi,

    I converted this application to .net framework 2012 and replaced Window.Identy.model to System.Identity.model . I found an issue like
    The name 'WSTrustFeb2005Constants' does not exist in the current context

    at


    RequestSecurityToken rst = new RequestSecurityToken {
    RequestType = WSTrustFeb2005Constants.RequestTypes.Issue,
    AppliesTo = new EndpointAddress(realm),
    KeyType = WSTrustFeb2005Constants.KeyTypes.Bearer,
    TokenType =System.IdentityModel .Tokens .SecurityTokenTypes.Saml
    };

    any suggestions

  • Eugene said

    This works with http://abc.sharepoint.com/teamsite (P plans), just FYI to you "plan p1".

    To anyone bumped into "System.NullReferenceException: Object reference not set to an instance of an object.":
    1. Check the run-time env. with the Windows Identity Foundation installed
    2. Check the PROXY on your network: some proxy does not support HTTP Expect: 100-continue header from .net framwork, so it just rejects the request BEFORE it reaches Sharepoint Online.

    Hope this will save someone's day!

  • Sriram Srinivasan said

    Thanks for the post Wictor, I receive an error message at this part of the code in MsOnlineClaimsHelper.cs file
    Message response = trustClient.EndIssue(
    trustClient.BeginIssue(
    Message.CreateMessage(
    MessageVersion.Default,
    WSTrustFeb2005Constants.Actions.Issue,
    new RequestBodyWriter(trustSerializer, rst)
    ),
    null,
    null));


    The error is -
    An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
    InnerException - Authentication Failure.

    Any idea why this is happening? I am giving the correct login details in the code but still not sure about this problem.

  • Michel said

    Thanks for sharing this!

    I have been searching high and low but cannot seem to find an example on how to do this active login using the credentials (cookies) of the current authenticated user.

    All examples seem to pass username and password.

    I found an example that works, using InternetGetCookieEx(), but this only works from a console application, not from my MVC4 web application.

    Any idea if this even possible?

    kr,
    Michel.

  • alex said

    Michel,

    you'll have trouble reading cookies depending on where you look. In the response, you won't have the cookies, as some cookies are registered as Http Only for security purposes.

    You need to either read the raw response (ugh) or go back to your request to get them there.

    However, in JavaScript, once you've authenticated, you should be alright, depending on the level of access you have. Site Collection admins, for instance, need an extra fedauth cookie.

  • Chris mauldin said

    Wictor,

    We have no problem connecting to a SPO 2010 site collection using claims based processing. But our Office 365 account was recently upgraded and we upgraded a test site to make sure everything is working.

    We can no longer connect using claims based authentication? Still works on the SPO 2010 site collections, but not any new or upgraded SPO 2013 site collects. The error message is:

    Error
    An error has occurred on the server.

    Troubleshoot issues with Microsoft SharePoint Foundation.

    Correlation ID: 37d0179c-2a67-6092-d368-4576f78ce048

    Date and Time: 5/3/2013 7:40:50 AM


    Any ideas or suggestions?

    HELP!!

    Chris M.

  • ceinture longchamp femme said

    Hi! This is kind of off topic but I need some guidance from an established blog. Is it tough to set up your own blog? I'm not very techincal but I can figure things out pretty quick. I'm thinking about creating my own but I'm not sure where to start. Do you have any ideas or suggestions? With thanks

  • Mitch Hughes said

    If you already have the username and password, you can use the new Microsoft.SharePoint.Client.SharePointOnlineCredentials class to provide the proper O365 credentials to ClientContext.Credentials.

  • Tyler said

    I'm currently researching a situation where users are logging in via a thin client and intend to use sky drive. They'd like to avoid having to sign into the browser prior to accessing their sky drives, and your solution looks like it could handle that. What I'm a bit confused about is where to put it. Any suggestions on how to handle that?

  • prix louboutin said

    naturally like your web site but you have to check the spelling on several of your posts. Several of them are rife with spelling issues and I find it very bothersome to tell the truth then again I will certainly come back again.

  • Tyler said

    I am trying to write an executable that will run just after a user logs in using their AD credentials, but I haven't had any luck. Does anyone know how to do this? I saw Michael mentioned finding a solution that does that, but he didn't post a link. I'd really like to see that.

  • Dave said

    Hey Wictor, this works great when I run it from Visual Studio in my WebService locally but when I publish it to the webserver IIS 6 it crashes on the CookieContainer.getCookieContainer().

    Any Ideas.

    Thanks

    Dave

  • Dave said

    I just wanted to add that I am using VS 2012 to connect to Office 365 sharepoint 2013.

    thanks

    Dave

  • Tyler said

    In my situation the user is already logged in via SSO with ADFS. Is there a way to just get the cookies since my user is already logged in? I don't see a need to log them in again.

  • Ariel Plon said

    Hi Wictor
    THANK YOU SO MUCH for this. We have been struggling for several days to connect our .Net app to Sharepoint. Our solution is in vb.net, and we are having trouble with this line of your code: "context.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;
    ". Would you please translate to vb? We have not been able to.
    Thanks in advanced.
    Best regards, Ariel

  • Andrew Filan said

    Hi everyone,

    Thank you Wictor for the sample. I am however struggling now for a few days already to get it working on my end. I am trying to implement a user control connecting to Sharepoint 365. I was getting (and I am still in fact) the error message which is already mentioned a few times in the discussion:

    getCookieContainer throwing an null exception

    This error message causes a bit of confusion, since in your code you are catching exceptions in the getSamlToken() method and returning null. That’s why we don’t get a relevant error message when running your code which makes debugging a bit more difficult. That said, the application throws an “Authentication Failure” exception. You can see the detailed error in this screenshot http://goo.gl/YoKBfs .
    Additionally, if I understand the basics of the OAuth protocol, I won’t be able to setup this example until I have a public facing URL, which the authentication server is able to access. At least that’s what I think is happening after watching this vide on Sharepoint 2013 OAuth implementation http://goo.gl/GC8XVG . This seems to be also confirmed when I try to generate my Client secret and Client id in Sharepoint 365 which shows me the following error (generated at https://<companyName>.sharepoint.com/_layouts/15/appregnew.aspx):

    Invalid app domain.
    Example: "www.contoso.com"

    If there is someone out there, who’s able to confirm this and maybe give me some clues if this is not the case, I would be really thankful.

    Anyways, thank you Wictor again for a great article a great code,
    Andrew

  • Herman Stevenson said

    Above given blog is one of the informative blog about How to active authentication to for SharePoint Online, and writer also gives all kind of technical detail for successfully competition on this task.

  • Anand kumar said

    Hi Wictor,

    your code works perfect while traversing folders.

    I'm getting "403 - forbidden" exception when i try to down load the file.

    could you help me with that.

    Thanks in advance

  • Warlock said

    Is it possible to get SAML token without providing user name and password in code? I want that a user get alert with notification from sharepoint web site with suggestion to provide user name and password.

  • Amogh said

    Thanks for great article! However I am not able to connect to the SharePoint Online Site with "microsoft" domain! I think this is happening because Microsoft have its own ADFS configured to login to the SharePoint online site.
    Is there any way to get through this? and do the authentication to such sharepoint online sites without any user interaction (HeadLess)?

    Any help in this is greatly appreciated.!

    Thanks in advance!

  • krunal said

    Hello,

    I want to create sharepoint online user using c# Can you help me?

    Thanks
    Krunal

  • SAM said

    hi Wictor, I am getting both cookies but now i want to display the user who loged in into site i.s want to display main site(Dashboard) for that user for other work .(like single sign on)

    Please help

  • Shaid said

    Hi I have deployed the claimshelper using VS2012 using using .net framework 4.5, when I consume the wcf from client windows app , I get the following error returned from the cloud webservice

    Could not load file or assembly 'Microsoft.SharePoint.Client, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified.

    In your sample there is a reference to this library otherwise how will it communicate with sharepoint online?

  • Girish Meena said

    Hello Raul

    "Raul Lopez said on Jul 4 2012 at 1:36 PM

    Hi Wictor.

    Thanks for your code. Work fine for me in windows form app.

    Now I try to run in a Metro style app (Framework 4.5) but not found in this framework (System.web.dll problems...).

    I am trying to update your code but do you have the code with framework 4.5? or do you think if that is possible?

    Saludos.

    Thanks."

    I am in same scenario. have you updated your code. if yes please share with us.

Add a Comment

AWS Tracker

About Wictor...

Wictor Wilén is a Director and SharePoint Architect working at Connecta AB. Wictor has achieved the Microsoft Certified Architect (MCA) - SharePoint 2010, Microsoft Certified Solutions Master (MCSM) - SharePoint  and Microsoft Certified Master (MCM) - SharePoint 2010 certifications. He has also been awarded Microsoft Most Valuable Professional (MVP) for four consecutive years.

And a word from our sponsors...

SharePoint 2010 Web Parts in Action