角色之间的Asp.net MVC让用户切换 [英] Asp.net MVC Let user switch between roles

查看:203
本文介绍了角色之间的Asp.net MVC让用户切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发展具有多重角色的用户一个复杂的网站。用户也连接上在DB的其他项目,它与他们的角色一起,将决定他们所能看到和做到在网站上。

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.

现在,一些用户具有超过1的作用,但该网站只能在一个时间处理,因为结构复杂1的作用。

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

的想法是,在用户登录,并在该网站,在那里他可以选择他的一个角色的角落下拉。如果他只有1个角色没有下拉列表。

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.

现在我在DB的最后选择的角色值存储与用户自己的其他设置。当他返回时,这种方式的作用还记得。

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. 存放在会话当前角色。

  2. 重写 IsInRole 方法或写在 IsCurrentlyInRole 方法来检查所有进入当前选定的角色,而不是所有角色一样,原来的 IsInRole

  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

有关会话的一部分存储我认为这会是好做,在的Global.asax

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;
                    }
                }
            }

        }
    }

但显然这给了运行时错误。 会话状态不可用在这方面。


  1. 如何解决这个问题,而这是
    真是最好的地方,把这个
    code?

  2. 如何扩展用户(的IPrincipal ?)和 IsCurrentlyInRole 不失所有其他功能

  3. 也许我做的这一切错误的,有一个更好的方式来做到这一点?

  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?

任何帮助是极大AP preciated。

Any help is greatly appreciated.

推荐答案

是的,你不能在Application_AuthenticateRequest访问会话。结果
我已经创建了自己的CustomPrincipal。我会告诉你什么,我最近做了一个例子:

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);  
    }
}

我的Application_AuthenticateRequest读取cookie,如果有一个身份验证票证(用户登录):

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);
    }
 }

我伸出我的饼干加入身份验证票证的的UserData。我在这里把额外的信息:

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

这是在登录电子后创建cookie的功能:

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;

这样你就可以访问您的自定义主要成员:currentPrincipal.ActiveRole

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

当用户改变它的作用(积极作用),你可以重写的cookie。

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

我忘了说,我在authTicket.UserData存储JSON序列化类,所以很容易反序列化和解析。

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

这篇关于角色之间的Asp.net MVC让用户切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆