1
votes

I have followed the following guide Forms-Authentication-and-Role-based-Authorization to implement custom membership authentication and authorization successfully. I was using sessions to get other user details such as First Name and Last Name. However session can be lost while auth cookie still exists/is valid. Now I want to be able to add user details to the cookie but not sure how to do it. Was thinking to add it to the roles string and grab it from there but not sure what are the implications. I have also seen this link Store data in auth cookie but it does not mention using roles.

Thus how would I get both roles and other user details as part of the cookie so I don't have to be hitting the database for such details?

Thanks.

2

2 Answers

0
votes

If you're creating persistent users with the Membership provider, you'd be better off storing the other user details in a similar persistent store that is independent of the user's browser.

Have you looked at the Profile provider, which allows you to store profile information alongside your membership data? This can work alongside the Membership and Roles providers, and even allows you to create a persistent profile for anonymous users that you can carry over once they register.

If you are sure that you don't want to use the Profile provider (and there are reasons not to), then by all means take a look at DanH's answer on using the UserData field the AuthToken - but be aware that you will need to be generating (or re-generating) the auth token yourself - I shouldn't worry about this not mentioning Roles, that should work alongside the existing methods quite nicely.

0
votes

Rather than the approach you linked to, I would create a custom RoleProvider.

As for the user details, I would keep it separate from the authentication / authorization logic. Either use a Profile Provider, as Zhaph - Ben Duguid suggested, or implement it yourself.

If you use Session to cache the user details, the fact that Session is not related to the authentication cookie is not a problem, as you can always refresh from the database if Session is lost.

Something like:

public UserDetails UserDetails
{
    get
    {
        UserDetails userDetails = Session["UserDetails"] as UserDetails;
        if (userDetails == null)
        {
            userDetails = GetUserDetailsFromDatabase(HttpContext.Current.User.Identity.Name);
            Session["UserDetails"] = userDetails;
        }
        return userDetails;
    }
}