Sylvain
Sylvain

Reputation: 19269

How to store info about the authenticated user in WCF?

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.

Upvotes: 3

Views: 783

Answers (1)

marc_s
marc_s

Reputation: 754868

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.

Upvotes: 2

Related Questions