C# - 自定义角色和成员身份提供程序背后的表单身份验证代码

发布于 2024-10-20 15:25:48 字数 5070 浏览 6 评论 0原文

不幸的是,我在网上找到的带有自定义角色和成员资格提供程序的表单身份验证代码隐藏的所有示例都是使用 VB.NET 代码编写的,而我需要 C# 代码隐藏。请帮忙!!!!

我需要一个代码隐藏来执行以下操作:

  • 在登录按钮单击时验证用户
  • 如果用户 active_flag=0 (假)或密码!=@password,则
  • ,显示错误:“访问被拒绝”如果用户 admin_flag=1 & 重定向到 admin_pages\zipsearch.aspx
  • active flag=1 (true),如果用户 admin_flag=0 (false) 则 active_flag=1(true),重定向到pages\zipsearch.aspx

Default.aspx 代码:

    <asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false">
    <LayoutTemplate>
        <span class="failureNotification">
            <asp:Literal ID="FailureText" runat="server"></asp:Literal>
        </span>
        <asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="failureNotification" 
             ValidationGroup="LoginUserValidationGroup"/>
        <div class="accountInfo">
            <fieldset class="login">
                <legend>Account Information</legend>
                <p>
                    <asp:Label ID="usernameLabel" runat="server" AssociatedControlID="username">Username:</asp:Label>
                    <asp:TextBox ID="username" runat="server" CssClass="textEntry"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="username" 
                         CssClass="failureNotification" ErrorMessage="User Name is required." ToolTip="User Name is required." 
                         ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
                </p>
                <p>
                    <asp:Label ID="passwordLabel" runat="server" AssociatedControlID="password">Password:</asp:Label>
                    <asp:TextBox ID="password" runat="server" CssClass="passwordEntry" TextMode="password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="passwordRequired" runat="server" ControlToValidate="password" 
                         CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required." 
                         ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
                </p>
                <p>
                    <asp:CheckBox ID="RememberMe" runat="server"/>
                    <asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label>
                </p>
            </fieldset>
            <p class="submitButton">
                <asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="LoginUserValidationGroup"/>
            </p>
        </div>
    </LayoutTemplate>
</asp:Login>

Web.config 文件:

<authentication mode="Forms">
  <forms loginUrl="~/default.aspx" timeout="2880" />
</authentication>

  <membership>
  <providers>
    <clear/>
      <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="OleConnectionStringSource"
         enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
         maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
         applicationName="/" />  
  </providers>
</membership> 

<profile>
  <providers>
    <clear/>
   <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/> 
  </providers>
</profile>

<roleManager enabled="false">
  <providers>
    <clear/>
      <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
    <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> 
  </providers>
</roleManager>

Default.aspx.cs 背后的代码:

namespace ACAWebApplication
{
  public partial class _Default : System.Web.UI.Page
  { 
     protected void Page_Load(object sender, EventArgs e)
     {
       RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);

       // authenticate user
       // if user active_flag=0 (false) OR password!=@password, display error: "Access Denied" 

       // if user admin_flag=1 & active flag=1 (true), redirect to admin_pages\zipsearch.aspx
       // if user admin_flag=0 (false) & active_flag=1 (true), redirect to pages\zipsearch.aspx

      }
   }
 }

非常感谢! :)

Unfortunately, all the examples for Forms Authentication Code Behind w/ Custom Role and Membership Providers I find online are written with a VB.NET code behind and I need a C# code behind. Please help!!!!

I need a codebehind that will do the following:

  • authenticate user upon login button click
  • if user active_flag=0 (false) OR password!=@password, display error: "Access Denied"
  • if user admin_flag=1 & active flag=1 (true), redirect to admin_pages\zipsearch.aspx
  • if user admin_flag=0 (false) & active_flag=1 (true), redirect to pages\zipsearch.aspx

Default.aspx Code:

    <asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false">
    <LayoutTemplate>
        <span class="failureNotification">
            <asp:Literal ID="FailureText" runat="server"></asp:Literal>
        </span>
        <asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="failureNotification" 
             ValidationGroup="LoginUserValidationGroup"/>
        <div class="accountInfo">
            <fieldset class="login">
                <legend>Account Information</legend>
                <p>
                    <asp:Label ID="usernameLabel" runat="server" AssociatedControlID="username">Username:</asp:Label>
                    <asp:TextBox ID="username" runat="server" CssClass="textEntry"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="username" 
                         CssClass="failureNotification" ErrorMessage="User Name is required." ToolTip="User Name is required." 
                         ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
                </p>
                <p>
                    <asp:Label ID="passwordLabel" runat="server" AssociatedControlID="password">Password:</asp:Label>
                    <asp:TextBox ID="password" runat="server" CssClass="passwordEntry" TextMode="password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="passwordRequired" runat="server" ControlToValidate="password" 
                         CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required." 
                         ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
                </p>
                <p>
                    <asp:CheckBox ID="RememberMe" runat="server"/>
                    <asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label>
                </p>
            </fieldset>
            <p class="submitButton">
                <asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="LoginUserValidationGroup"/>
            </p>
        </div>
    </LayoutTemplate>
</asp:Login>

Web.config file:

<authentication mode="Forms">
  <forms loginUrl="~/default.aspx" timeout="2880" />
</authentication>

  <membership>
  <providers>
    <clear/>
      <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="OleConnectionStringSource"
         enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
         maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
         applicationName="/" />  
  </providers>
</membership> 

<profile>
  <providers>
    <clear/>
   <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/> 
  </providers>
</profile>

<roleManager enabled="false">
  <providers>
    <clear/>
      <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
    <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> 
  </providers>
</roleManager>

Default.aspx.cs code behind:

namespace ACAWebApplication
{
  public partial class _Default : System.Web.UI.Page
  { 
     protected void Page_Load(object sender, EventArgs e)
     {
       RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);

       // authenticate user
       // if user active_flag=0 (false) OR password!=@password, display error: "Access Denied" 

       // if user admin_flag=1 & active flag=1 (true), redirect to admin_pages\zipsearch.aspx
       // if user admin_flag=0 (false) & active_flag=1 (true), redirect to pages\zipsearch.aspx

      }
   }
 }

Thanks a lot in advance! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

森末i 2024-10-27 15:25:48

首先,您可以使用登录方法:

protected void LoginButton_Click(object sender, EventArgs e)
{
 // Validate the user against the Membership framework user store
 if (Membership.ValidateUser(UserName.Text, Password.Text))
 {
 // Log the user into the site
 FormsAuthentication.RedirectFromLoginPage(UserName.Text, RememberMe.Checked);
 }
 // If we reach here, the user's credentials were invalid
 InvalidCredentialsMessage.Visible = true;
}

您可以在身份验证方法中检查用户凭据:

protected void myLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
 // Get the email address entered
 TextBox EmailTextBox = myLogin.FindControl("Email") as TextBox;
 string email = EmailTextBox.Text.Trim();

 // Verify that the username/password pair is valid
 if (Membership.ValidateUser(myLogin.UserName, myLogin.Password))
 {
 // Username/password are valid, check email
 MembershipUser usrInfo = Membership.GetUser(myLogin.UserName);
 if (usrInfo != null && string.Compare(usrInfo.Email, email, true) == 0)
 {
 // Email matches, the credentials are valid
 e.Authenticated = true;
 }
 else
 {
 // Email address is invalid...
 e.Authenticated = false;
 }
 }
 else
 {
 // Username/password are not valid...
 e.Authenticated = false;
 }
}

要根据特定角色进行重定向,请使用以下代码:

protected void Login1_LoggedIn(object sender, EventArgs e)
{
    if (Roles.IsUserInRole(Login1.UserName, "Admin"))
    {
         Response.Redirect("~/Admin/Default.aspx");
    }
    else if (Roles.IsUserInRole(Login1.UserName, "User"))
    {
         Response.Redirect("~/User/Default.aspx");
    }
    else if (Roles.IsUserInRole(Login1.UserName, "Viewer"))
    {
         Response.Redirect("~/Viewer/Default.aspx");
    }
    else
    {
         Response.Redirect("~/Login.aspx");
    }
}

编辑:

这是应该适合您的解决方案,不是最好的代码,而是还可以。

因此,首先使用 DestinationPageUrl 标记配置登录控件,如下所示:

<asp:Login 
  ID="Login1" 
  runat="server" 
  DestinationPageUrl="~/admin_pages/zipsearch.aspx">
</asp:Login>

然后在 LoginButton_Click 方法中:

 protected void LoginButton_Click(object sender, EventArgs e)
    {
     // Validate the user against the Membership framework user store
    if (Membership.ValidateUser(myLogin.UserName, myLogin.Password))
     {
     // Username/password are valid, check email
     MembershipUser currentUser = Membership.GetUser(myLogin.UserName);

        if (currentUser != null)
        {
            if (admin_flag == true)
              {
                     FormsAuthentication.RedirectFromLoginPage(UserName.Text, RememberMe.Checked);
            }
           else
              {
              // If we reach here, the user's credentials were invalid -> your access is denied message
             InvalidCredentialsMessage.Visible = true;
            }
        }
      }
      //if code goes here validation of user failed        
    }

to make a start here you go with the login method:

protected void LoginButton_Click(object sender, EventArgs e)
{
 // Validate the user against the Membership framework user store
 if (Membership.ValidateUser(UserName.Text, Password.Text))
 {
 // Log the user into the site
 FormsAuthentication.RedirectFromLoginPage(UserName.Text, RememberMe.Checked);
 }
 // If we reach here, the user's credentials were invalid
 InvalidCredentialsMessage.Visible = true;
}

you can check the user credentials within the authenticate method:

protected void myLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
 // Get the email address entered
 TextBox EmailTextBox = myLogin.FindControl("Email") as TextBox;
 string email = EmailTextBox.Text.Trim();

 // Verify that the username/password pair is valid
 if (Membership.ValidateUser(myLogin.UserName, myLogin.Password))
 {
 // Username/password are valid, check email
 MembershipUser usrInfo = Membership.GetUser(myLogin.UserName);
 if (usrInfo != null && string.Compare(usrInfo.Email, email, true) == 0)
 {
 // Email matches, the credentials are valid
 e.Authenticated = true;
 }
 else
 {
 // Email address is invalid...
 e.Authenticated = false;
 }
 }
 else
 {
 // Username/password are not valid...
 e.Authenticated = false;
 }
}

For redirection depending on a specific role use this code:

protected void Login1_LoggedIn(object sender, EventArgs e)
{
    if (Roles.IsUserInRole(Login1.UserName, "Admin"))
    {
         Response.Redirect("~/Admin/Default.aspx");
    }
    else if (Roles.IsUserInRole(Login1.UserName, "User"))
    {
         Response.Redirect("~/User/Default.aspx");
    }
    else if (Roles.IsUserInRole(Login1.UserName, "Viewer"))
    {
         Response.Redirect("~/Viewer/Default.aspx");
    }
    else
    {
         Response.Redirect("~/Login.aspx");
    }
}

EDIT:

Here is the solution which should work for you not the best code but still ok.

So first of all you make configure your login control with the DestinationPageUrl tag like this:

<asp:Login 
  ID="Login1" 
  runat="server" 
  DestinationPageUrl="~/admin_pages/zipsearch.aspx">
</asp:Login>

Then in your LoginButton_Click method:

 protected void LoginButton_Click(object sender, EventArgs e)
    {
     // Validate the user against the Membership framework user store
    if (Membership.ValidateUser(myLogin.UserName, myLogin.Password))
     {
     // Username/password are valid, check email
     MembershipUser currentUser = Membership.GetUser(myLogin.UserName);

        if (currentUser != null)
        {
            if (admin_flag == true)
              {
                     FormsAuthentication.RedirectFromLoginPage(UserName.Text, RememberMe.Checked);
            }
           else
              {
              // If we reach here, the user's credentials were invalid -> your access is denied message
             InvalidCredentialsMessage.Visible = true;
            }
        }
      }
      //if code goes here validation of user failed        
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文