Question

I am trying to use SimpleMembershipProvider for FormsAuthentication. Now this provider internally creates a FormsAuth cookie without any additional userdata.

I want to include some other information in the cookie such as UserId, Role, etc

I have implemented following-


public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (isAuthorized)
        {
            var formsCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            var identity = new AppUserIdentity(string.Empty, true);
            if (formsCookie != null)
            {
                var cookieValue = FormsAuthentication.Decrypt(formsCookie.Value);
                if (cookieValue != null && !string.IsNullOrEmpty(cookieValue.UserData))
                {
                    var cookieData = SerializerXml.Deserialize<UserNonSensitiveData>(cookieValue.UserData);
                    identity = new AppUserIdentity(cookieValue.Name, cookieData.UserId, true);
                }
                else if (cookieValue != null)
                {
                    //TODO: Find out technique to get userid value here
                    identity = new AppUserIdentity(cookieValue.Name, null, true);
                }
            }

            var principal = new AppUserPrincipal(identity);
            httpContext.User = Thread.CurrentPrincipal = principal;
        }
        return isAuthorized;
    }
}

This attribute is decorated on all required controller methods. When a user registers or login on the website I am updating the cookie as well with additional userdata (serialized string)

var newticket = new FormsAuthenticationTicket(ticket.Version,
                                                      ticket.Name,
                                                      ticket.IssueDate,
                                                      ticket.Expiration,
                                                      ticket.IsPersistent,
                                                      userdata,
                                                      ticket.CookiePath);

        // Encrypt the ticket and store it in the cookie
        cookie.Value = FormsAuthentication.Encrypt(newticket);
        cookie.Expires = newticket.Expiration.AddHours(24);

        Response.Cookies.Set(cookie);

However, in MyAuthorizeAttribute it never gets userdata in the cookie. Is there anything wrong in the above code? Or something missing somewhere else?

Was it helpful?

Solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top