Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3974888
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T04:37:15+00:00 2026-05-20T04:37:15+00:00

I’m developing a complex website with users having multiple roles. The users are also

  • 0

I’m developing a complex website with users having multiple roles. The users are also coupled on other items in the DB which, together with their roles, will define what they can see and do on the website.

Now, some users have more than 1 role, but the website can only handle 1 role at a time because of the complex structure.

the idea is that a user logs in and has a dropdown in the corner of the website where he can select one of his roles. if he has only 1 role there is no dropdown.

Now I store the last-selected role value in the DB with the user his other settings. When he returns, this way the role is still remembered.

The value of the dropdown should be accessible throughout the whole website.
I want to do 2 things:

  1. Store the current role in a Session.
  2. Override the IsInRole method or write a IsCurrentlyInRole method to check all access to the currently selected Role, and not all roles, as does the original IsInRole method

For the Storing in session part I thought it’d be good to do that in Global.asax

    protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
        if (User != null && User.Identity.IsAuthenticated) {
            //check for roles session.
            if (Session["CurrentRole"] == null) {
                NASDataContext _db = new NASDataContext();
                var userparams = _db.aspnet_Users.First(q => q.LoweredUserName == User.Identity.Name).UserParam;
                if (userparams.US_HuidigeRol.HasValue) {
                    var role = userparams.aspnet_Role;
                    if (User.IsInRole(role.LoweredRoleName)) {
                        //safe
                        Session["CurrentRole"] = role.LoweredRoleName;
                    } else {
                        userparams.US_HuidigeRol = null;
                        _db.SubmitChanges();
                    }
                } else {
                    //no value
                    //check amount of roles
                    string[] roles = Roles.GetRolesForUser(userparams.aspnet_User.UserName);
                    if (roles.Length > 0) {
                        var role = _db.aspnet_Roles.First(q => q.LoweredRoleName == roles[0].ToLower());
                        userparams.US_HuidigeRol = role.RoleId;
                        Session["CurrentRole"] = role.LoweredRoleName;
                    }
                }
            }

        }
    }

but apparently this gives runtime errors. Session state is not available in this context.

  1. How do I fix this, and is this
    really the best place to put this
    code?
  2. How do I extend the user (IPrincipal?) with IsCurrentlyInRole without losing all other functionality
  3. Maybe i’m doing this all wrong and there is a better way to do this?

Any help is greatly appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T04:37:15+00:00Added an answer on May 20, 2026 at 4:37 am

    Yes, you can’t access session in Application_AuthenticateRequest.
    I’ve created my own CustomPrincipal. I’ll show you an example of what I’ve done recently:

    public class CustomPrincipal: IPrincipal
    {
        public CustomPrincipal(IIdentity identity, string[] roles, string ActiveRole)
        {
            this.Identity = identity;
            this.Roles = roles;
            this.Code = code;
        }
    
        public IIdentity Identity
        {
            get;
            private set;
        }
    
        public string ActiveRole
        {
            get;
            private set;
        }
    
        public string[] Roles
        {
            get;
            private set;
        }
    
        public string ExtendedName { get; set; }
    
        // you can add your IsCurrentlyInRole 
    
        public bool IsInRole(string role)
        {
            return (Array.BinarySearch(this.Roles, role) >= 0 ? true : false);  
        }
    }
    

    My Application_AuthenticateRequest reads the cookie if there’s an authentication ticket (user has logged in):

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[My.Application.FORMS_COOKIE_NAME];
        if ((authCookie != null) && (authCookie.Value != null))
        {
            Context.User = Cookie.GetPrincipal(authCookie);
        }
    }
    
    
    public class Cookie
        {
        public static IPrincipal GetPrincipal(HttpCookie authCookie)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            if (authTicket != null)
            {
                string ActiveRole = "";
                string[] Roles = { "" };
                if ((authTicket.UserData != null) && (!String.IsNullOrEmpty(authTicket.UserData)))
                {
                // you have to parse the string and get the ActiveRole and Roles.
                ActiveRole = authTicket.UserData.ToString();
                Roles = authTicket.UserData.ToString();
                }
                var identity = new GenericIdentity(authTicket.Name, "FormAuthentication");
                var principal = new CustomPrincipal(identity, Roles, ActiveRole );
                principal.ExtendedName = ExtendedName;
                return (principal);
            }
            return (null);
        }
     }
    

    I’ve extended my cookie adding the UserData of the Authentication Ticket. I’ve put extra-info here:

    This is the function which creates the cookie after the loging:

        public static bool Create(string Username, bool Persistent, HttpContext currentContext, string ActiveRole , string[] Groups)
        {
            string userData = "";
    
            // You can store your infos
            userData = ActiveRole + "#" string.Join("|", Groups);
    
            FormsAuthenticationTicket authTicket =
                new FormsAuthenticationTicket(
                1,                                                                // version
                Username,
                DateTime.Now,                                                     // creation
                DateTime.Now.AddMinutes(My.Application.COOKIE_PERSISTENCE),       // Expiration 
                Persistent,                                                       // Persistent
                userData);                                                        // Additional informations
    
            string encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket);
    
            HttpCookie authCookie = new HttpCookie(My.Application.FORMS_COOKIE_NAME, encryptedTicket);
    
            if (Persistent)
            {
                authCookie.Expires = authTicket.Expiration;
                authCookie.Path = FormsAuthentication.FormsCookiePath;
            }
    
            currentContext.Response.Cookies.Add(authCookie);
    
            return (true);
        }
    

    now you can access your infos everywhere in your app:

    CustomPrincipal currentPrincipal = (CustomPrincipal)HttpContext.User;
    

    so you can access your custom principal members: currentPrincipal.ActiveRole

    When the user Changes it’s role (active role) you can rewrite the cookie.

    I’ve forgot to say that I store in the authTicket.UserData a JSON-serialized class, so it’s easy to deserialize and parse.

    You can find more infos here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
I am trying to understand how to use SyndicationItem to display feed which is
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have a text area in my form which accepts all possible characters from
I know there's a lot of other questions out there that deal with this
I'm trying to select an H1 element which is the second-child in its group

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.