如何使用表单身份验证根据用户的角色在登录后重定向到不同的页面? [英] How do I redirect to different page after login based on user's role using form authentication?

查看:75
本文介绍了如何使用表单身份验证根据用户的角色在登录后重定向到不同的页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有2个用户角色: - 学生,老师。



有3种类型的用户: - 管理员,学生,教师。



管理员的用户名和密码不存储在数据库中,所以直接用实际的用户名和密码检查。



学生和教师的用户名和密码存储在数据库中,因此在登录时会检查用户名和密码,并根据他们的角色重定向到他们的特定页面。



我使用表单身份验证,以便只合法用户可以访问他们的页面。但是当我运行LoginPage时,我收到错误(下面)。



错误: -

There are 2 user roles :- Student, Teacher.

There are 3 type of users :- admin, Students, Teachers.

Admin's username and password is not store in the database so it is directly check with actual username and password.

Student's and Teacher's username and password is stored in the database so during login username and password is check and redirect to their specific page based on their role.

I used form authentication so that only legitimate user can access their page. But I am getting error(below) when I am running LoginPage.

error:-

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /default.aspx

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1069.1





我的尝试:



LoginPage.aspx.cs





What I have tried:

LoginPage.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Security;


public partial class Registration_LoginPage : System.Web.UI.Page
{
    Code code = new Code();
    SqlConnection con;
    SqlCommand cmd;
    bool flag = true;

    public Registration_LoginPage()
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        cmd = new SqlCommand();
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        { 

        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.Now);
        Response.Cache.SetNoServerCaching();
        Response.Cache.SetNoStore();
        }

        if(User.Identity.Name !=String.Empty)
        {
            FormsAuthentication.RedirectFromLoginPage(User.Identity.Name, false);
        }

    }

    protected void btnLogIn_Click(object sender, EventArgs e)
    {
       // String encryptedPassword = code.encrypt(Request.Form["password"]);

        try
        { 
            con.Open();
            cmd.CommandText = "select * from [Users]";
            cmd.Connection = con;
            SqlDataReader rd = cmd.ExecuteReader();
            

            if (Request.Form["username"] == "admin" && Request.Form["password"] == "admin")
            {
                Session["Username"] = Request.Form["username"];
                Response.Redirect("/AdminHome/AdminMPage.aspx");
            }
            else
            {

                while (rd.Read())
                {

                if (rd["UserName"].ToString() == Request.Form["username"] && rd["Password"].ToString() == Request.Form["password"])
                    {
                        Session["Username"] = rd["UserName"];
                        flag = false;
                        break;
                    }
                }
                if (flag == true)
                    lblMsg.Text = "Username and password invalid";
                else
                {
                string roles = rd["Role"].ToString();
                if (rd["Role"].ToString() == "Student")
                        //  Response.Redirect("Student.aspx");
                        FormsAuthentication.RedirectFromLoginPage(roles, false);

                    /* else
                         Response.Redirect("Teacher.aspx");  */

                  else  if (rd["Role"].ToString() == "Teacher")
                        FormsAuthentication.RedirectFromLoginPage(roles, false);
                }
            }
      } 
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;

        } 
    }
    
}







web.config






web.config

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

  <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True"

        providerName="System.Data.SqlClient" />
  </connectionStrings>

    <system.web>
      
      <authentication mode="Forms">
        <forms loginUrl="/Registration/LoginPage.aspx">
        </forms>
      </authentication>

      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />
    </system.web>
  
  <location path="FIRST PAGE">
      <system.web>
        <authorization>
          <allow users="*"/>
          
        </authorization>
      </system.web>
    </location>
  
  <location path="Registration">
      <system.web>
        <authorization>
          <allow users="*"/>
          
        </authorization>
      </system.web>
    </location>
  
  
    <location path="AdminHome">
      <system.web>
        <authorization>
          <allow users="admin"/>
          <deny users="*"/>
        </authorization>
      </system.web>
    </location>
  
  <location path="Student">
      <system.web>
        <authorization>
          <allow roles="Student"/>
          <deny users="*"/>
        </authorization>
      </system.web>
    </location>
  
<location path="Teacher">
      <system.web>
        <authorization>
          <allow roles="Teacher"/>
          <deny users="*"/>
        </authorization>
      </system.web>
    </location>

  <appSettings>

    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
    
  </appSettings>
  

</configuration>

推荐答案

在你的网址中使用〜。这意味着您网站的根目录。



Use the ~ in your url. That means the root of your site.

Response.Redirect("~/AdminHome/AdminMPage.aspx");


这是一个例子





This is an example


<authentication mode="Forms">
  <forms loginUrl="Login.aspx" name="adAuthCookie" timeout="120" path="/"/>
</authentication>







protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        if ((bool)Session["CambiarContraseña"] == true)
        {
            Response.RedirectPermanent("CambiarContrasena.aspx?c=1");
        }
        else
        {
            if (User.Identity.IsAuthenticated)
            {
                txtFecha.Text = DateTime.Now.ToShortDateString();

            }
            else
            {
                Server.Transfer("Login.aspx");

            }
        }

    }
}


这篇关于如何使用表单身份验证根据用户的角色在登录后重定向到不同的页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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