开发者

Asp.net MVC Let user switch between roles

开发者 https://www.devze.com 2023-02-12 04:26 出处:网络
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 we

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.


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


If you truly want the user to only have 1 active role at a time (as implied by wanting to override IsInRole), maybe it would be easiest to store all of a user's "potential" roles in a separate place, but only actually allow them to be in 1 ASP.NET authentication role at a time. When they select a new role use the built-in methods to remove them from their current role and add them to the new one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号