I thought that I would spend a little time talking about authenticating against SharePoint via a web service. This is something that most people will encounter if they wish to access information from a SharePoint list where SharePoint is secured via forms authentication.
Steps to authenticate (see example code below):
- Create a web reference to one of the authentication web service instances within SharePoint. It does not matter which one, so I usually just use the base one. In my example, I called the web reference “wsAuth”. The URL will follow the format “http(s)://mysharepointsite/_vti_bin/Authentication.asmx”.
- Create an instance of a cookie container and set it in the service. It will be used to maintain stateful communication with the web service and will be populated with the authentication information when you call the “Login” method.
- Set the URL if you wish to login to a specific section of the site. Note that the URL of the web reference will always default back to the base instance (regardless of where you create the web reference to).
- Call the “Login” method and get the result.
If successful, the cookie container will now have all of the necessary information for future calls to services that require authentication. You will need to set this object to the cookie container of the instance of a service (similar to below) and you should be able to successfully call the services on your SharePoint site. Note that the access to the site will be limited to that of the username/password being authenticated.
::begin code sample::
internal const string URL_AUTHENTICATION = "/_vti_bin/Authentication.asmx";
internal static CookieContainer Authenticate(string siteUrl, string username, string password)
{
CookieContainer cookieJar = new CookieContainer();
wsAuth.Authentication service = null;
wsAuth.LoginResult result;
try
{
service = new wsAuth.Authentication();
service.Url = siteUrl + URL_AUTHENTICATION;
service.CookieContainer = cookieJar;
result = service.Login(username, password);
switch (result.ErrorCode)
{
case wsAuth.LoginErrorCode.NoError:
//authentication was a success
break;
case wsAuth.LoginErrorCode.NotInFormsAuthenticationMode:
//there was an error with the authentication mode
break;
case wsAuth.LoginErrorCode.PasswordNotMatch:
//the username and/or password were invalid
break;
}
}
finally
{
if (service != null)
service.Dispose();
}
return cookieJar;
}
::end code sample::
No comments:
Post a Comment