views:

80

answers:

1

I have a WCF service where I use a customUserNamePasswordValidatorType (specified in the behaviors\serviceBehaviors\serviceCredentials\userNameAuthentication section of the web.config file).

My custom UserNamePasswordValidator works that way:

public bool Authenticate(string userName, string password)
{
     If ( IsUserValid(username, password) )
    {
        UserInfo currentUser = CreateUserInfo(username);
       //
       // Here I'd like to store the currentUser object somewhere so that
       // it can be used during the service method execution
       //
       return true;
    }
    return false;

}

During the service call execution, I need to access the info of the authenticated user. For instance I would like to be able to implement:

public class MyService : IService
{
     public string Service1()
    { 
       //
       // Here I'd like to retrieve the currentUser object and use it
       //
       return "Hello" + currentUser.Name;
    }
}

My question is how and where should I store the information during the authentication process so that it can be accessed during the call execution process? That storage should only last as long as the "session" is valid.

By the way, I don't use (and don't want to use) secure sessions and/or reliable sessions. So I have both establishSecuritytContext and reliableSessions turned off.

I'm thinking of enabling ASP.NET Compatibility Mode to store the user info in the HttpContext.Current.Session but I have the feeling it's not how it should be done.

+2  A: 

Store anything that needs to be persisted into a persistant store - e.g. a database, that's the best way to go.

Store the user info in a user table, e.g. the ASP.NET membership system or something of your own. Keep some kind of a identifying token (username, ID etc.) at hand to retrieve that info from the database when needed.

You should strive to have a stateless WCF service whenever possible - it should never depend on a "state" of any kind other than what's safely stored in a database.

marc_s
Ok, but during the service execution, how will I retrieve the username of the current user so that I can look it up in the database?
Sly
You should be able to check the `ServiceSecurityContext.Current.PrimaryIdentity` in every service call. That should contain the IIdentity for the currently authenticated user
marc_s
That primary identity has a "Name" property which should be the user name of the currently authenticated user; use that as your "entry point" to more user info in a database table
marc_s
Thank you very much! I did not know about `ServiceSecurityContext.Current.PrimaryIdentity`. That is in fact they way I really wanted to do that.
Sly
@Sly: ok, great to know!
marc_s