ASP.NET Authentication

后端 未结 1 1072
悲哀的现实
悲哀的现实 2021-01-23 23:39

I have the following a login page where the user enters in their username and password.

With that info, I need to then make sure that they are part of the Admin1 role If

相关标签:
1条回答
  • 2021-01-23 23:57

    User.IsInRole("Admin1") is false right after validation, because principal object hasn't been attached to the current HttpContext yet.

    If you really want to use Context.User, you need to manually attach principal object.

    var username = txtUserName.Text;
    var password = txtPassword.Text;
    
    if (Membership.ValidateUser(username , password))
    {
        var roles = Roles.GetRolesForUser(username);
        var identity = new GenericIdentity(username);
        var principal = new GenericPrincipal(identity, roles);
        Context.User = principal;
    
        // Now you can use Context.User
    
        // Basically User.IsInRole("Admin1") is same as roles.Contains("Admin1")
        if (User.IsInRole("Admin1"))
        {
            FormsAuthentication.SetAuthCookie(username, true);
        }
    }
    

    Updated - Authenticate user using Login Control

    Since you are using Membership Provider and Role Provider, I would like to suggest to use Login Control.

    Once user is authenticated, you can use LoggedIn event to redirect user to appropiate page.

    <asp:Login ID="LoginUser" runat="server" EnableViewState="false" 
       RenderOuterTable="false" OnLoggedIn="LoginUser_LoggedIn">
       ...
    </asp:Login>
    
    protected void LoginUser_LoggedIn(object sender, EventArgs e)
    {
       // Now we know that user is authenticated
       // Membership user = Membership.GetUser(Login1.Username);
       var roles = Roles.GetRolesForUser(Login1.Username);
    
       if(roles.Contains("Admin1"))
          Response.Redirect("~/Admin/");
       else
          Response.Redirect("~/Users/");       
    }
    
    0 讨论(0)
提交回复
热议问题