gpt4 book ai didi

asp.net-mvc - Asp.net MVC 让用户在角色之间切换

转载 作者:行者123 更新时间:2023-12-04 06:34:20 25 4
gpt4 key购买 nike

我正在开发一个具有多个角色的用户的复杂网站。用户还与 DB 中的其他项目相关联,这些项目与他们的角色一起将定义他们在网站上可以看到和执行的操作。

现在有的用户有1个以上的角色,但由于结构复杂,网站一次只能处理1个角色。

这个想法是用户登录并在网站的角落有一个下拉菜单,他可以在其中选择他的角色之一。如果他只有 1 个角色,则没有下拉列表。

现在我将最后选择的角色值与用户的其他设置一起存储在数据库中。当他回来时,这样的角色仍然被记住。

下拉列表的值应该可以在整个网站上访问。
我想做两件事:

  • 将当前角色存储在 Session 中.
  • 覆盖 IsInRole方法还是写个IsCurrentlyInRole方法来检查对当前选定角色的所有访问权限,而不是所有角色,原始 IsInRole 也是如此。方法

  • 对于 session 中的存储部分,我认为最好在 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;
    }
    }
    }

    }
    }

    但显然这会导致运行时错误。 Session state is not available in this context.
  • 我该如何解决这个问题,这是
    真的是最好的地方放这个
    代码?
  • 如何使用 IPrincipal 扩展用户( IsCurrentlyInRole ?)不会丢失所有其他功能
  • 也许我做错了,有更好的方法来做到这一点?

  • 任何帮助是极大的赞赏。

    最佳答案

    是的,您无法在 Application_AuthenticateRequest 中访问 session 。
    我已经创建了自己的 CustomPrincipal。我将向您展示我最近所做的一个例子:

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

    我已经扩展了我的 cookie,添加了身份验证票的 UserData。我在这里放了额外的信息:

    这是在登录后创建 cookie 的函数:
        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);
    }

    现在您可以在您的应用中随处访问您的信息:
    CustomPrincipal currentPrincipal = (CustomPrincipal)HttpContext.User;

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

    当用户更改其角色(主动角色)时,您可以重写 cookie。

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

    您可以找到更多信息 here

    关于asp.net-mvc - Asp.net MVC 让用户在角色之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5030227/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com