I am sort of new with creating web service using WCF. I just have a quick question. I am validating the user using SimpleMembershipProvider. In some calls to my web service, I need to retrieve the current userid. So, I am using WebSecurity.CurrentUserId which I used in MVC.NET.
To explain better, here is my web.config and as you can see, I am using custom validator:
<system.serviceModel>
...
...
...
<behaviors>
<serviceBehaviors>
<behavior name="behaviorCfg">
...
...
...
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WarehouseWebService.WarehouseValidator, WarehouseWebService" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
...
...
...
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="0" multipleSiteBindingsEnabled="true" />
<system.serviceModel>
Here is my custom validator (WarehouseValidator.cs):
public class WarehouseValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (!WebSecurity.Initialized)
WebSecurity.InitializeDatabaseConnection("warehouseConnStr", "UserProfile", "UserId", "UserName", false);
if (!WebSecurity.Login(userName, password, true))
throw new FaultException("Invalid username or password.");
}
}
Now, in some calls (functions) on the webservice, I need to get the CurrentUserId and I am using WebSecurity.CurrentUserId, but it returns -1.
All other property also seems not being initialized. For example, WebSecurity.CurrentUserName is empty and WebSecurity.IsAuthenticated is false.
This is weird because WebSecurity.Login(userName, password, true) is successful and I am using the same method in my website (MVC.NET) and it worked fine.
I know it is something to do with the cookies, I even tried to do:
FormsAuthentication.SetAuthCookie(userName, true);
But nothing has worked so far!
Any idea why?
Cheers
if you are using
FormsAuthentication.SetAuthCookie(userName, true);you need to setaspNetCompatibilityEnabledtotruein your config file, it stating that your services will participate in the ASP.NET pipeline; so items like ASP.NET cookies are available.so try by adding