pjacko
pjacko

Reputation: 562

ServiceStack Session always null in MVC Controller

I'm creating an ASP.NET MVC 4 app using the service stack MVC powerpack, utilizing service stack's auth and session providers. I'm copying lot of logic from the social bootstrap API project. My controllers inherit from the following base controller:

public class ControllerBase : ServiceStackController<CustomUserSession>

which is implemented as:

public class ControllerBase : ServiceStackController<CustomUserSession> {}

CustomUserSession inherits from AuthUserSession:

public class CustomUserSession : AuthUserSession

After I log in, my CustomUserSession OnAuthenticated() method runs, but when I redirect back to my controller, the UserSession is not populated, e.g.

public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
    base.OnAuthenticated(authService, session, tokens, authInfo);
    CustomFoo = "SOMETHING CUSTOM";

    // More stuff
}

public class MyController : ControllerBase
{
    public ActionResult Index()
    {
        // After having authenticated
        var isAuth = base.UserSession.IsAuthenticated; // This is always false
        var myCustomFoo = base.UserSession.CustomFoo; // This is always null

    }
}

Can anyone see what I'm missing here?

Upvotes: 4

Views: 1404

Answers (2)

paaschpa
paaschpa

Reputation: 4816

Refer to issue within ServiceStack Google Group - https://groups.google.com/forum/?fromgroups=#!topic/servicestack/5JGjCudURFU

When authenticating with a JsonSeviceClient (or any serviceClient) from within MVC the cookies are not shared with MVC request/response.

When authenticating within a MVC Controller to ServiceStack, the MVC HttpContext should be sent to ServiceStack. Something like below should work...

var authService = AppHostBase.Resolve<AuthService>();
authService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
var response = authService.Authenticate(new Auth
{
  UserName = model.UserName,
  Password = model.Password,
  RememberMe = model.RememberMe
});

Upvotes: 2

paaschpa
paaschpa

Reputation: 4816

Try setting IsAuthenticated to true and saving your session...

public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
    base.OnAuthenticated(authService, session, tokens, authInfo);
    CustomFoo = "SOMETHING CUSTOM";
    session.IsAuthenticated = true;
    authService.SaveSession(session);

    // More stuff
}

Upvotes: 1

Related Questions