How to update the UserSession to Redis?

I used the AuthFeature.

 Plugins.Add(new AuthFeature(() => new CustomUserSession(),
          new IAuthProvider[]
          {
              new BasicAuthProvider(),    //Sign-in with Basic Auth
              new CredentialsAuthProvider(),
          }));

the follow code is works fine. the after UserSession.UserName = 123

UserSession.UserName = "456"
UserSession.UserName = "123";
logger.Info($"After: {UserSession.UserName}");

After I Used the

  container.Register<IRedisClientsManager>(
                   c => new PooledRedisClientManager($"password@{RedisServer}:port"));
        container.Register(c =>
                    c.Resolve<IRedisClientsManager>().GetCacheClient());

then the UserSession.UserName = “456”. not changed . I found it the UserAuth used the Redis cache.
How to update the UserSession to Reids?

ServiceStack’s User Session is just a normal POCO, you need to Save the Session in order for it to persist to the registered ICacheClient, e.g:

var userSession = base.Request.GetSession();
userSession.UserName = "123";
base.Request.SaveSession(userSession);
1 Like

Yes, you are right! I used the the controller inherit from ServiceStackController.

  1. In the ServiceStackController It has UserSession, Is there any difference between the UserSession and the under userSession?
var userSession = base.Request.GetSession();
  1. If I used the base.Request.GetSession(), when after Authenticate, the userSession’s SessionId will changed. Why it will changed?

This Question isn’t clear, but GetSession() returns the Users Session.

Again question isn’t clear, but you may be referring to the Generate new Session Cookies on Authentication behavior, which was added for additional security.

sorry. In your source code, It Has AuthSession, UserSession, and the above base.Request.GetSession() , I have some confused with these Session, is there any document can find the difference?

namespace ServiceStack.Mvc
{
    public abstract class ServiceStackController<T> : ServiceStackController where T : IAuthSession
    {
        protected ServiceStackController();

        public IAuthSession AuthSession { get; }
        protected T UserSession { get; }
    }
}

Here’s the source code for ServiceStackController:

public abstract class ServiceStackController<T> : ServiceStackController
    where T : IAuthSession
{
    protected T UserSession
    {
        get { return SessionAs<T>(); }
    }

    public IAuthSession AuthSession
    {
        get { return UserSession; }
    }
}

It’s the same instance casted into the IAuthSession interface.

Tip: You can easily locate source code by going to the GitHub - ServiceStack/ServiceStack: Thoughtfully architected, obscenely fast, thoroughly enjoyable web services for all repo and clicking T which will start quick find mode where you can then start typing the name of the file to filter the results.