想做一个.NET的教学管理系统,分为教师、学生和管理员三种角色,不同的角色登录后进入不同的页面,请问用什么方式对角色进行定义比较好呢?在登录页面用什么对角色进行判断呢?

解决方案 »

  1.   

    1:在用户的session中加入用户的角色信息,这样你在判断时就可以直接得到了。
    2:用户的一些profile信息最好也加载进session,除了一些极占资源的之外。
    比如:用户登录成功后跳转到哪个页面,用户的名称,部门====。
      

  2.   

    login.aspx
    Imports System.Web
    Imports System.Web.UI.Webcontrols
    Imports Microsoft.VisualBasic
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Web.Security
    Public Class ValidateUser
        Inherits System.Web.UI.Page
    Protected WithEvents tbUserName As System.Web.UI.WebControls.TextBox
    Protected WithEvents tbPwd As System.Web.UI.WebControls.TextBox
    Protected WithEvents pn As System.Web.UI.WebControls.Panel
    Protected WithEvents tbNewPwd1 As System.Web.UI.WebControls.TextBox
    Protected WithEvents tbNewPwd2 As System.Web.UI.WebControls.TextBox
    Protected WithEvents cb As System.Web.UI.WebControls.CheckBox
    Protected WithEvents btnLogin As System.Web.UI.WebControls.Button
    Protected WithEvents btnReset As System.Web.UI.WebControls.Button
    Protected WithEvents btnChaPwd As System.Web.UI.WebControls.Button
    Protected WithEvents lblMsg As System.Web.UI.WebControls.Label
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()    End Sub
        Private designerPlaceholderDeclaration As System.Object
        Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
            InitializeComponent()

        End Sub
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            If Not ispostback Then
                pn.visible = False
            End If
        End Sub
    Private Sub btnLogin_onclick(ByVal Sender As System.Object,ByVal e As System.EventArgs) Handles btnLogin.click
    'It is setting cookie expiration
    dim intMinutes as integer
    if cb.checked then
    intMinutes = 30
    else
    intMinutes = 1
    end if

    if ValidateUser(Trim(tbUserName.text),Trim(tbPwd.text)) then
    if btnChaPwd.Enabled = true then
    Dim conn2 As SqlConnection
    Dim cmd2 As SqlCommand
    ' string to use to connect to your local SQL Server.
                    conn2 = New SqlConnection("Server= ;uid= ;pwd= ;database= ")
    conn2.Open()
    ' Create SqlCommand to select pwd field from the users table given a supplied userName.
    dim strcmd2 as string
                    strcmd2 = "Select UserRoles from BIU_UserRoles Where UserId='" & Ucase(trim(tbUserName.text)) & "'"
    cmd2 = New SqlCommand(strcmd2, conn2)
    Dim dr As SqlDataReader
    dr = cmd2.ExecuteReader()
    if dr.read() then
    '创建一个新的验证票FormsAuthenticationTicket
    'cookie版本、名、过期日期、发布日期、持久性以及用户定义的数据
    Dim ticket As New FormsAuthenticationTicket( _
    1, _
    Ucase(trim(tbUserName.text)), _
    System.DateTime.Now, _
    System.DateTime.Now.AddDays(intMinutes), _
    false, _
    dr.GetString(0)) '指定从dr的第0列取出字符串的值
    '用户数据:可用 ((System.Web.Security.FormsIdentity)User.Identity).Ticket.UserData 获取
    '把验证票加密
    Dim encTicket As String = FormsAuthentication.Encrypt(ticket)
    '声明一个 Cookie,名称为 Web.config 中 <forms name=".APSX" … /> 的 name 属性,对应的值为身份验票加密后的字串
    dim ck as System.Web.HttpCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName,encTicket)        
    '指定 Cookie 为 Web.config 中 <forms path="/" … /> path 属性,不指定则默认为“/”
    ck.Path = System.Web.Security.FormsAuthentication.FormsCookiePath
    '设置Cookie的有效期
    ck.Expires = System.DateTime.Now.AddDays(intMinutes)
    '设置验证票cookie,第一个参数为cookie的名字,第二个参数为cookie的值也就是加密后的票
    Response.Cookies.Add(ck)
    ' Redirect back to original URL.
    Response.Redirect(FormsAuthentication.GetRedirectUrl(Ucase(trim(tbUserName.text)),false))
    else 
    lblMsg.text = "Not Add to User Roles"
    end if
    ' Cleanup command and connection objects.
    dr.close
    cmd2.Dispose()
    conn2.Dispose()
    else
    if tbNewPwd1.Text <> "" and tbNewPwd2.Text <> "" and (Trim(tbNewPwd1.Text)=Trim(tbNewPwd2.Text)) Then
                        Dim conn As New SqlConnection("Server=172.19.34.9;uid=watchdb;pwd=fifwat;database=watchDB")
    conn.open()
    '更新用户密码
    dim strCmd as string
    strcmd = "UPDATE UserList SET UserPwd = '" & Trim(tbNewPwd1.Text) & "' WHERE UserId = '" & Trim(tbUserName.Text) & "'"
    dim ChangePwd as new sqlcommand
    ChangePwd.Connection = conn
    ChangePwd.CommandType = CommandType.Text
    ChangePwd.CommandText = strcmd
    ChangePwd.ExecuteNonQuery()
    ChangePwd.dispose()

    'Create Forms Authentication Ticket
    Dim cmd2 As SqlCommand
    ' Create SqlCommand to select pwd field from the users table given a supplied userName.
    dim strcmd2 as string
                        strcmd2 = "Select UserRoles from BIU_UserRoles Where UserId='" & Ucase(trim(tbUserName.text)) & "'"
    cmd2 = New SqlCommand(strcmd2, conn)
    Dim dr As SqlDataReader
    dr = cmd2.ExecuteReader()
    if dr.read() then
    '创建一个新的验证票FormsAuthenticationTicket
    'cookie版本、名、过期日期、发布日期、持久性以及用户定义的数据
    '登录用户名:对应 Web.config 中 <allow users="Admin" … /> 的 users 属性
    Dim ticket As New FormsAuthenticationTicket( _
    1, _
    Ucase(trim(tbUserName.text)), _ 
    System.DateTime.Now, _
    System.DateTime.Now.AddDays(intMinutes), _
    false, _
    dr.GetString(0)) '指定从dr的第0列取出字符串的值
    '用户数据:可用 ((System.Web.Security.FormsIdentity)User.Identity).Ticket.UserData 获取
    '把验证票加密
    Dim encTicket As String = FormsAuthentication.Encrypt(ticket)
    '声明一个 Cookie,名称为 Web.config 中 <forms name=".APSX" … /> 的 name 属性,对应的值为身份验票加密后的字串
    dim ck as System.Web.HttpCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName,encTicket)        
    '指定 Cookie 为 Web.config 中 <forms path="/" … /> path 属性,不指定则默认为“/”
    ck.Path = System.Web.Security.FormsAuthentication.FormsCookiePath
    '设置Cookie的有效期
    ck.Expires = System.DateTime.Now.AddDays(intMinutes)
    '设置验证票cookie,第一个参数为cookie的名字,第二个参数为cookie的值也就是加密后的票
    Response.Cookies.Add(ck)
    ' Redirect back to original URL.
    Response.Redirect(FormsAuthentication.GetRedirectUrl(Ucase(trim(tbUserName.text)),false))
    else 
    lblMsg.text = "Not Add to User Roles"
    end if
    ' Cleanup command and connection objects.
    dr.close
    cmd2.Dispose()
    MessageBox("密码已修改!",Page)
    else
    lblMsg.Text = "New Password not correct!"
    end if
    end if
    else
    lblMsg.text = "Input Validation of User Name or Password failed"
    'lblMsg.text = format(System.DateTime.Now.AddDays(intMinutes),"yyyyMMdd")
    end if
    End Sub
     
    End Class
      

  3.   

       Private Sub btnReset_onclick(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.click
            If btnChaPwd.Enabled = True Then
                tbUserName.text = ""
                tbPwd.text = ""
            Else
                pn.visible = False
                btnChaPwd.Enabled = True
            End If
        End Sub
        Private Sub btnChaPwd_onclick(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles btnChaPwd.click
            pn.visible = True
            btnChaPwd.Enabled = False
            btnReset.Text = "取消"
        End Sub
        '++++++++++++++++++++++++++
        'Validate User 
    Private Function ValidateUser(ByVal userId As String, ByVal passWord As String) As Boolean
            ' Check for an invalid userName.
            ' userName  must not be set to nothing and must be between one and 15 characters.
            If (userId ="") Then
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.")
                Return False
            End If
            If ((userId.Length = 0) Or (userId.Length > 9)) Then
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.")
                Return False
            End If
            ' Check for invalid passWord.
            ' passWord must not be set to nothing and must be between one and 20 characters.
            If (passWord  ="") Then
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.")
                Return False
            End If
            If ((passWord.Length = 0) Or (passWord.Length > 20)) Then
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.")
                Return False
            End If

            Dim conn As SqlConnection
            Dim cmd As SqlCommand
            Dim lookupPermission As String

            lookupPermission = ""
            'Try
                ' string to use to connect to your local SQL Server.
            conn = New SqlConnection("Server= ;uid= ;pwd= ;database= ")
                conn.Open()            ' Create SqlCommand to select pwd field from the users table given a supplied userName.
    dim strcmd as string
            strcmd = "Select UserPermission from UserList Where UserId='" & Ucase(trim(UserId)) & "' And UserPwd='" & Trim(Password) & "'"
                cmd = New SqlCommand(strcmd, conn)
                ' Execute command and fetch pwd field into lookupPassword string.
                lookupPermission = cmd.ExecuteScalar()

                ' Cleanup command and connection objects.
                cmd.Dispose()
                conn.Dispose()
            'Catch ex As Exception
                ' Add error handling here for debugging.
                ' This error message should not be sent back to the caller.
                'System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " & ex.Message)
            'End Try        ' If no password found, return false.

            If (lookupPermission = "") Then
                ' You could write failed login attempts here to the event log for additional security.
                Return False
            End If        ' Compare lookupPassword and input passWord by using a case-sensitive comparison.
            Return (Instr(1,lookupPermission,"S") or Instr(1,lookupPermission,"B") or Instr(1,lookupPermission,"R"))
    End Function
    '++++++++++++++++++++++++++
    '弹出错误信息
    Private Function MessageBox(ByVal strText As String, ByVal objPage As System.Web.UI.Page)
    Dim IidScript As String
            Dim strWindow As String
            strWindow = "window.alert('" & strText & "')"
            IidScript = "<script>" & strWindow & "</" & "script>"
            If (Not IsClientScriptBlockRegistered("failure")) Then
                RegisterClientScriptBlock("failure", IidScript)
            End If
        End Function