nova
nova

Reputation: 175

How can I rename default session cookie names in servicestack

ServiceStack has the default cookie names "ss-id" "ss-pid" and "ss-opt" defined in SessionFeature.cs

Is there a way to change the default names to something else?

The configuration code in HostConfig doesn't seem to reference it.

Would appreciate any tips/pointers.

Upvotes: 4

Views: 607

Answers (2)

DannyW
DannyW

Reputation: 99

A further case for configurable cookie names is that you may have say an MVC site at domain.com and an api at api.domain.com. If you take advantage of servicestack's session capabilities in both (but with separate logins), the ss-id etc cookies will fight each other on the two sites. This is the case in IE and Edge, where domain and subdomain cookies are always shared, whereas in Chrome the cookies remain separate.

We have exactly this configuration - an MVC site at domain.com, and various subdomains hosting apis for variations of our app. As soon as someone used IE rather than Chrome this broke the separate of cookies between the MVC site and the subdomains.

Unfortunately the filter solution above does not work for the servicestack MVC integration. It is too late for us to switch from domain.com to www.domain.com so we cannot currently enjoy servicestack's session storage on the MVC site.

I have requested the feature change.

Upvotes: 1

Scott
Scott

Reputation: 21511

As you've noted in the SessionFeature.cs code the cookie names are defined as const, and are not user configurable.

You could however use filters to change the cookie names to something more suitable on request and response. Add to your configure method:

const string mySessionIdentifier = "mySessionId";

// Converts incoming requests with "mySessionId" cookie to "ss-id"
PreRequestFilters.Add((IRequest httpReq, IResponse httpRes) =>
{
    var cookie = httpReq.Cookies[mySessionIdentifier];
    if (cookie != null)
    {
        httpReq.Cookies.Remove(mySessionIdentifier);
        httpReq.Cookies.Add(ServiceStack.Keywords.SessionId, cookie);
    }
}


// Converts responses with outgoing cookie "ss-id" to "mySessionId"
GlobalResponseFilters.Add((IRequest httpReq, IResponse httpRes, object dto) => {
    var cookies = httpRes.CookiesAsDictionary();
    string cookie;
    if (cookies.TryGetValue(ServiceStack.Keywords.SessionId, out cookie))
    {
        httpRes.DeleteCookie(ServiceStack.Keywords.SessionId);
        httpRes.SetCookie(new Cookie(mySessionIdentifier, cookie));
    }
});

You could also suggest here that this is configurable.

Upvotes: 4

Related Questions