Reputation: 14912
I am retrieving the tenant name from the url. I'd prefer to do it only once, store it in the cookie, and retrieve it from there when I need it in a new page request.
I am using the code below to "create" a cookie. I was hoping that the interface would allow me to store additional information but it doesn't. Is there a way to do this or am I on the wrong track?
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName))
throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
thanks in advance.
Upvotes: 9
Views: 7512
Reputation: 39807
The FormsAuthenticationExtensions project on codeplex and on Nuget does exactly this. https://archive.codeplex.com/?p=formsauthext
Usage -Setting Values
using FormsAuthenticationExtensions;
using System.Collections.Specialized;
var ticketData = new NameValueCollection
{
{ "name", user.FullName },
{ "emailAddress", user.EmailAddress }
};
new FormsAuthentication().SetAuthCookie(user.UserId, true, ticketData);
Usage -Retrieving Values
using FormsAuthenticationExtensions;
using System.Web.Security;
var ticketData = ((FormsIdentity) HttpContext.Current.User.Identity).Ticket.GetStructuredUserData();
var name = ticketData["name"];
var emailAddress = ticketData["emailAddress"];
Basically, you can append a name/value dictionary inside of your FormsAuthentication cookie to store some frequently used values. We leverage this store store a small subset of user information such as companyId, etc.
Additionally, there is no 'black magic' happening here, it is simply encapsulating the setting/retrieving of the UserData property inside of the FormsAuthentication Ticket
As for consideration, please be sure to read the notes at the bottom of the project page as it describes why this should only be used for small amounts of long-living data.
Upvotes: 14
Reputation: 7605
Personally, I wouldn't try to alter the Auth Cookie. Instead, create a new cookie:
var myCookie = new HttpCookie("myCookie");//instantiate an new cookie and give it a name
myCookie.Values.Add("TenantName", "myTenantName");//populate it with key, value pairs
Response.Cookies.Add(myCookie);//add it to the client
Then you can read the value on that's written to the cookie like this
var cookie = Request.Cookies["myCookie"];
var tenantName = cookie.Values["TenantName"].ToString();
//tenantName = "myTenantName"
Upvotes: 7