Home » Azure

How to create SPUser or SPUserToken from Username and Password (Forms-based Authentication)

Hi all,

I need to connect and work with SharePoint Document Library, while my console application is external and running aside the SharePoint context. The SharePoint applicaiton is running with Forms Based Authentication (FBA).

I think I need to instantiate an impersonated SPSite object, but in order to do that I need SPUserToken object.

Is there any way to create an instance of SPUserToken or SPUser object by providing Username and Password?

Thanks in advance.







5 Answers Found


Answer 1

You can't instantiate  an SPSIte object  if you're working outside the sharepoint  context. You have to use web services to communicate with sharepoint from an external  application.

With web services this is how you can pass credentials:


System.Net.NetworkCredential MyCredentials = new NetworkCredential(UserName, Password, Domain);

WebService.Lists DevList = new WebService.Lists();
DevList.Credentials = MyCredentials ;



Answer 2

Hi Karla,


Thanks for your response.

What I'm actually trying to do is to add a new document  to Document Library in SPSite with FBA.

I didn't find a Web Service method allowing to do that. 

Could you please point me to the relevant one?




Answer 3

Hi MishaSoft,


Do you want to upload a document  or add a new document? If you want to upload a file to the document library, you can user the Cope web Service to achieve it.

Web Service: CopyWeb Reference: http://<Site>/_vti_bin/Copy.asmx


More information:




Answer 4

Hi Wane,

Thanks for your reply. It seems I did one step forward.

FieldInformation fi = new FieldInformation();
CopyResult[] res = null;
Copy cpy = new Copy();
cpy.Credentials = new NetworkCredential("spadmin", "******", "");
uint rc = cpy.CopyIntoItems(
        newstring[] { "http://mysrv/docs/doclib/doc.txt" },
        new FieldInformation[] { fi },
        out res);

Now I success to upload the file to server with Windows based  authenitcaiton, but it still doesn't work  for environment with forms  Based authentication. I provide the forms user credentials through Copy.Credentials property, but it throws the following exception:  

The request failed with the error message:
<html><head><title>Object moved</title></head><body><h2>Object moved to <ahref="%2f_layouts%2flogin.aspx%3fReturnUrl%3d%252f_vti_bin%252fCopy.asmx">here</a>.</h2></body></html>

It seems the server ignores the credentials and redirects the WS request to login.aspx

Any ideas how I can authenticate the Forms-based user ?




Answer 5

Thanks to all for the help.

I've finally figured out the solution.

      Authentication auth = new Authentication();
      auth.CookieContainer = new CookieContainer();
      auth.AllowAutoRedirect = true;
      LoginResult lrc = auth.Login ("spadmin", "******");

      //Upload the file
      FieldInformation fi = new FieldInformation();
      CopyResult[] res = null;
      Copy cpy = new Copy();
      cpy.CookieContainer = auth.CookieContainer;
      uint rc = cpy.CopyIntoItems(
        new string[] { "http://mysrv/docs/doclib/doc.txt" },
        new FieldInformation[] { fi },
        out res);


Hello there!

For the life of me, i can't figure out why SharePoint keeps putting the phrase "i:0#.w|" infront of everyones username / accounts. Both on mysite and portal sites. A quick bing search revelaed that i am not the only one: http://fangdahai.blogspot.com/2010/06/i0w-is-still-there-in-sharepoint-2010.html.

Anyone have a solution to fix this annoying problem?



I have a repository for users that access my data, right in Azure platform. There will exist a client app installed on premises on user's computer that will access data in cloud via an Azure WCF Web Role.

How can I use ACS to authenticate and authorize each user in my solution ? Each request has to be aware of the user that called the method on server. I cannot rely on any OpenID system in my solution.



I have been trying (and failing) to configure a WCF Data Service with UserName/Password authentication via a SqlMembershipProvider. Depending on how I configure things, I either get no authentication whatsoever or I get Windows authentication. The latest version of the configuration file looks like this:

<?xmlversion="1.0"encoding="UTF-8"?><configuration><system.web><compilationdebug="true"targetFramework="4.0"/><membershipdefaultProvider="SqlProvider"userIsOnlineTimeWindow="15"><providers><clear/><addname="SqlProvider"type="System.Web.Security.SqlMembershipProvider"connectionStringName="PatchStore"applicationName="MembershipProvider"enablePasswordRetrieval="false"enablePasswordReset="false"requiresQuestionAndAnswer="false"requiresUniqueEmail="true"passwordFormat="Hashed"/></providers></membership></system.web><system.serviceModel><bindings><webHttpBinding><bindingname="RoleBinding"><securitymode="Transport"><transportclientCredentialType="Basic"/></security></binding></webHttpBinding></bindings><behaviors><serviceBehaviors><behaviorname="RoleBehavior"><!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --><serviceMetadatahttpGetEnabled="true"/><!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --><serviceDebugincludeExceptionDetailInFaults="true"/><serviceCredentials><userNameAuthenticationuserNamePasswordValidationMode="MembershipProvider"membershipProviderName="SqlProvider"/></serviceCredentials></behavior></serviceBehaviors></behaviors><services><servicename="PatchService.PatchStore"behaviorConfiguration="RoleBehavior"><endpointaddress="/PatchService/PatchStore.svc"binding="webHttpBinding"bindingConfiguration="RoleBinding"contract="System.Data.Services.IRequestHandler"/></service></services><serviceHostingEnvironmentmultipleSiteBindingsEnabled="true"aspNetCompatibilityEnabled="true"/></system.serviceModel><system.webServer><modulesrunAllManagedModulesForAllRequests="true"/></system.webServer><connectionStrings><addname="PatchStoreEntities"connectionString="metadata=res://*/PatchModel.csdl|res://*/PatchModel.ssdl|res://*/PatchModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.;Initial Catalog=PatchStore;Integrated Security=True;MultipleActiveResultSets=True&quot;"providerName="System.Data.EntityClient"/><addname="PatchStore"connectionString="Data Source=.;Initial Catalog=PatchStore;Integrated Security=True;MultipleActiveResultSets=True"providerName="System.Data.SqlClient"/></connectionStrings></configuration>



Presently Basic Authentication is installed and enabled on the application in IIS. In this configuration, authentication appears to be handled by Windows.



I have a website developed in ASP.NET created by someone else, sitting on another server... until now... a simple(ish) setup with login to update content.

The site was zipped up and I was told it would be a simple case of uploading all the files onto the new server.  I've managed to upload the site and it works fine... but I can't access the editing pages as it will no longer accept the username and password when I go to login.

The host server is running ASP.NET v4 and IIS v7.  Hosting is with godaddy.com so I'm also getting used to their way of doing things.

Hope someone can help.



My hosting is DiscountASP.NET

 I get Error "Keyset does not exist".

Please, see error on page: http://www.healthbucket.com/HealthbucketWCF/wcfUser.svc

Section in my web.config of wcf looks:
<serviceCertificate findValue="www.healthbucket.com" storeLocation="LocalMachine"
storeName="My" x509FindType="FindBySubjectName" />
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="UsernameValidator, App_code" />

I think there are two errors:
1. CryptographicException: Keyset does not exist
2. The certificate 'CN=www.healthbucket.com, OU=Domain Control Validated - RapidSSL(R), OU=See www.rapidssl.com/resources/cps (c)08, OU=GT10747045, O=www.healthbucket.com, C=IL' must have a private key that is capable of key exchange. The process must have access rights for the private key.]

 * I have SSL installed on my hosting and configuration is correct.

I ask technical support of DiscountASP.NET and they tell me "issue that you are having is programmatically ".


Please help me.

What I do wrong???



I have the following problem:

I have a web application configured for claims based authentication. At the moment there is only NTLM-authentication enabled for this application. I have successfully added a site collection with a site collection administrator from our dmz domain (also farm admin). I now want to add users from our "normal" domain to the site collection.

I do this in http://SERVER/_layouts/people.aspx?MembershipGroupId=5 (Members). I use the "new" button and then the peoplepicker. The peoplepicker finds the ad-user, but when I click the "add"-button, I get an errormessage saying: "User does not exist" (free translation from German). The error in the logfile sais: Error in resolving user 'USERNAME'. System.ArgumentException: The provided value for the {0} parameter is not supported (again free translation).

However, if I add the user to the user policy in central administration everything works fine. But since we created custom user groups on our SharePoint 2010 we need to be able to use the peoplepicker and the SharePoint group management.

I provide the username as "domain\username". System used is a SharePoint 2010 Enterprise inside a dmz with trusted domains.


Is there any way to add the custom authenticator for ADFS 2.0 from management console?


Is it done only through modifying web.config in /adfs/ls?






i am new to this as i am learning. i have been assigned this project with vb express 2010 with access 2007 database (.accdb)

my database has a table named users which contains username, password & usertype fields. the usertype contains either "admin" or "limited user".

now i want to design a login form that has username, password fields as well as a field for usertype (this field obviously would be readonly), now please help me design such a login form.




I would like to create a login form and have the users input a user name and password to access the application. I am using Visual Studio 2008.  I've created table that I name PasswordUI in my database.  I also created two fields in the table called UserName and Password.  I then went into Visual Studio and used the login template that I want to use as the interface for the UserName and Password.   What I would like to do at this point is to have the UserName and Password validated by the table and then grants access.  Or can I just write the code within the command click (button) to grant access to the user.  The application I designing will only have four users, however each user may have a different set of permission.


guys, i need your help...

i setup web application using claim based + sqlmembership..

in  a form, i got password recovery control..

so, how can i retrieve the user password ???

currently, when i click submit button, i got an error as follow :

[NotImplementedException: The method or operation is not implemented.] Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider.GetUser(String name, Boolean userIsOnline) +62 System.Web.Security.MembershipProvider.GetUser(String username, Boolean userIsOnline, Boolean throwOnError) +35 System.Web.UI.WebControls.PasswordRecovery.AttemptSendPasswordUserNameView() +120 System.Web.UI.WebControls.PasswordRecovery.OnBubbleEvent(Object source, EventArgs e) +127 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981

p/s: note that i'm using sharepoint 2010 RTM and successfully configure smtp in server...

thanks in advance....


I'm getting an error 1326(logon failure) at the end of this code.  I'm copying this straight from a C++ version I did.  Is there going to be any difference because I'm using C#?



            var nr = new NETRESOURCE();
            var wd = new WSADATA();

            status = WSAStartup(36, ref wd);

            nr.dwScope = 1;
            nr.dwType = 1;
            nr.dwDisplayType = 3;
            nr.dwUsage = 1;
            nr.lpLocalName = null;
            nr.lpRemoteName = String.Format("\\\\{0}\\IPC$", args[0]);
            nr.lpComment = null;
            nr.lpProvider = null;

            status = WNetAddConnection2(nr, "", "", 1);

            var pipeHandle =
                  string.Format(@"\\{0}\pipe\browser", args[0]),
                  GENERIC_READ | GENERIC_WRITE,
//err == 1326
            int err = Marshal.GetLastWin32Error();


I have implemented forms authentication with ssrs 2008 r2. The problem is when I try to go to report builder it prompts for a user name and password. This doesn't work with the way we have our authentication setup. I have tried adding implementing the following:


but it still prompts for a username and password. Is there a way around this?

We developed our Intranet with FBA accessing Active Directory. I tweaked the providers and users can find using the name of the provider with colon PROVIDER:login@domain.com smoothly but that happened when using that fantastic BDC , I CAN'T ALLOW all users authenticated by the FBA to run that application BDC! 

Actions already performed.

- I extended the SharedService (SSP) and configured to work with FBA.
- I can allow a user (one by one) to ex.: PROVIDER:login@domain.com able to execute BDC app.
- I can add a group PROVIDERROLE:Users, PROVIDERROLE:Domain Users and any another group in Active Directory, but even with the permissions, users who belong to this group Active Directory unable to perform.
- I applied all permissions (BDC application in question) to the user ex.: PROVIDER:SPAccess used in the Web.Config to access Active Directory, set in the PROVIDER.
- I inserted the NT AUTHORITY \ Authenticated Users but only works with Windows Authentication.

For anonymous access used in this lab could solve the AllowAnonymousExecute true, the XML definition of the BDC application, but is difficult to authenticate! I would like something AllowAuthenticatedExecute.

Has anyone experienced this?


Hi All,

We have a site configured for forms based authentication in sharepoint 2010.We are using SQL server 2008 reporting services for generating reports from the database and using report viewer webpart to display these reports. The reports are working fine with windows authentication but failing for forms authentication. Can anyone please help us ?


I'm running SharePoint Server 2010 on a server 2008R2 box the SQL server is behind a firewall. I have setup FBA for a external document site but am unable to login. I can see my users in the membership DB in CA and was able to add them without problems. As I test I replicated this on a server inside the firewall and had no problems at all, which would lead me to think that it is a permissions issue. Any insight would be greatly appreciated. Here's the error I'm getting after sign-on:

The requested service, 'http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc' could not be activated. See the server's diagnostic trace logs for more information.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ServiceModel.ServiceActivationException: The requested service, 'http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc' could not be activated. See the server's diagnostic trace logs for more information.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ServiceActivationException: The requested service, 'http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc' could not be activated. See the server's diagnostic trace logs for more information.]

 System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +10258154

 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +539

 Microsoft.IdentityModel.Protocols.WSTrust.IWSTrustContract.Issue(Message message) +0

 Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst, RequestSecurityTokenResponse& rstr) +61

 Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst) +36

 Microsoft.SharePoint.SPSecurityContext.SecurityTokenForContext(Uri context, Boolean bearerToken, SecurityToken onBehalfOf, SecurityToken actAs, SecurityToken delegateTo) +26062081

 Microsoft.SharePoint.SPSecurityContext.SecurityTokenForFormsAuthentication(Uri context, String membershipProviderName, String roleProviderName, String username, String password) +172

 Microsoft.SharePoint.IdentityModel.Pages.FormsSignInPage.GetSecurityToken(Login formsSignInControl) +188

 Microsoft.SharePoint.IdentityModel.Pages.FormsSignInPage.AuthenticateEventHandler(Object sender, AuthenticateEventArgs formAuthenticateEvent) +123

 System.Web.UI.WebControls.Login.AttemptLogin() +152

 System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +124

 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70

 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29

 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981


 and here is what I'm seeing in the log file:


06/29/2010 11:29:49.38  w3wp.exe (0x1810)                        0x19E0 SharePoint Foundation          Logging Correlation Data       xmnv Medium   Name=Request (POST: 367e7875-a387-4ec9-b549-eb7847c0db6b
06/29/2010 11:29:49.38  w3wp.exe (0x1810)                        0x19E0 SharePoint Foundation          Logging Correlation Data       xmnv Medium   Site=/ 367e7875-a387-4ec9-b549-eb7847c0db6b
06/29/2010 11:29:49.41  w3wp.exe (0x1810)                        0x19E0 SharePoint Foundation          General                        8e2s Medium   Unknown SPRequest error occurred. More information: 0x80070005 367e7875-a387-4ec9-b549-eb7847c0db6b
06/29/2010 11:29:49.77  w3wp.exe (0x1810)                        0x19E0 SharePoint Foundation          Claims Authentication          fsq7 High     Request for security token failed with exception: System.ServiceModel.ServiceActivationException: The requested service, 'http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc' could not be activated. See the server's diagnostic trace logs for more information.    Server stack trace:      at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding)     at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)     at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)     at System.ServiceModel.Dispatcher.RequestChann... 367e7875-a387-4ec9-b549-eb7847c0db6b
06/29/2010 11:29:49.77* w3wp.exe (0x1810)                        0x19E0 SharePoint Foundation          Claims Authentication          fsq7 High     ...elBinder.Request(Message message, TimeSpan timeout)     at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)     at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)     at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)    Exception rethrown at [0]:      at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)     at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)     at Microsoft.IdentityModel.Protocols.WSTrust.IWSTrustContract.Issue(Message message)     at Microsoft.IdentityModel.Protocols.WSTru... 367e7875-a387-4ec9-b549-eb7847c0db6b
06/29/2010 11:29:49.77* w3wp.exe (0x1810)                        0x19E0 SharePoint Foundation          Claims Authentication          fsq7 High     ...st.WSTrustChannel.Issue(RequestSecurityToken rst, RequestSecurityTokenResponse& rstr)     at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst)     at Microsoft.SharePoint.SPSecurityContext.SecurityTokenForContext(Uri context, Boolean bearerToken, SecurityToken onBehalfOf, SecurityToken actAs, SecurityToken delegateTo) 367e7875-a387-4ec9-b549-eb7847c0db6b
06/29/2010 11:29:49.77  w3wp.exe (0x1810)                        0x19E0 SharePoint Foundation          Claims Authentication          8306 Critical An exception occurred when trying to issue security token: The requested service, 'http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc' could not be activated. See the server's diagnostic trace logs for more information.. 367e7875-a387-4ec9-b549-eb7847c0db6b

Thanks in advance for any help,



I am new to Active Directory Federation Services 2.0.
I was wondering if I present user with a login page (like passport does) using AD FS and use a SQL backend for maintaining user name / password for authentication (rather than using Windows authentication).

As of now AD FS does not seem to provide this option fom wizards and shows federation features only by windows authentication across domains.

I understand that I could build 1 custom STS to do that, but could I customize AD FS to use custom membership Providers for authentication and a SQL database to store / provision claims per replying party?

Please advise.



  I'm trying to edit the "My Profile" page using SharePoint deigner.  But I'm getting the following message from SPD when I try to open the page:

  Unable to open Web site.  Possible causes:

  1.  The Web server may not have SharePoint Server installed.

  2.  The Web server may be temporarily out of service.

  3.  If you are copnnecting through a proxy server, the proxy settings may be incorrect.

  4.  An error may have occurred in the Web server.


I am logged into the site using a site administrator account.  And I'm selecting, "Edit in SharePoint Designer" from the Site Actions menu.  Here's my current guess...  My "My Site" page is using Forms-based authentication.  Can the designer authenticate using forms-based authentication?




I am tasked to implement Singl Sign On for our 3 websites on 3 web servers in same domain (Active Direcotry).
web servers are:


Web01 hosts a logon page where the users are being redirected if they request website on Web02 or Web03. User enters his domain credentials that are first checked using "using System.DirectoryServices;" namespace. If valid user is not redirected back to the original requested page. the message appears "
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /welcomepage/Default.aspx

it seems like "/welcomepage/Default.aspx" is being searched on Web01 server where logon.aspx is hosted.

I dont understand why its trying to find default.aspx page on same server, why cant it go to original server Web02 that initiated this request.

also "Request.QueryString["ReturnUrl"];" returns only "/welcomepage/default.aspx" instead complete url

any help will be much appriciated

Many thanks


We are using SharePoint 2007 on Windows Server 2008. We have installed SharePoint 2007, Sql server 2008. I do not have Visual Studio on this server.  I want to use Form based authentication. I have configured each & every thing but I am not able to assign a user to site collection and also not in user policy.

I saw some links & followed instruction but not able to use FAB, Link is (which I saw):







I have followed instruction given in all sites one by one but not able to get user s from sql server.



 I am trying to setup Forms Based Authentication.  I have been following this guide:


At the point where i am attempting to set the Web Application .NET Users Default Provider to be 'i' (which is the Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider) i get an error telling me the provider is not trusted, i have done 2 things both of which give the same error.

in the administration.config file for IIS 7 i have added the provider into the trusted providers list in the administration.config file for IIS 7 i have set the allowuntrustedproviders to be true

Both things result in IIS 7 now allowing me through the inital error of not being trusted, however i now get a new error which is:

There was an error while performing this operation


Object Reference not set to an instance of an object.

Has anyone got any experience of this? or came up against the same error? how did you get around it?



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure