簡體   English   中英

無法使用 MSSQL Server 檢索 asp.net 中的角色

[英]unable to retrieve the role in asp.net with MSSQL Server

I am working with asp.net and MSSQL server for development of online application, I like to add roles and Membership in website, membership and roles are stored in SQL Server, I tried and successes for login with SQL Users and while i change the code for restricted訪問特定角色該角色未在頁面上列出。 我的頁面代碼如下:

登錄

        Dim userId As Integer = 0
        Dim roles As String = String.Empty
        Dim constr As String = ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("Validate_User")
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.AddWithValue("@Username", Username.Text)
                cmd.Parameters.AddWithValue("@Password", Password.Text)
                cmd.Connection = con
                con.Open()
                Dim reader As SqlDataReader = cmd.ExecuteReader()
                reader.Read()
                userId = Convert.ToInt32(reader("UserId"))
                roles = reader("Roles").ToString()
                con.Close()
            End Using
            con.Close()
        End Using
        Select Case userId
            Case -1
                errorText.Visible = True
                errorText.Text = "Username and/or password is incorrect."
                Exit Select
            Case Else
                Dim ticket As New FormsAuthenticationTicket(1, Username.Text, DateTime.Now, DateTime.Now.AddMinutes(1), True, roles,
                FormsAuthentication.FormsCookiePath)
                Dim hash As String = FormsAuthentication.Encrypt(ticket)
                Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, hash)
                If ticket.IsPersistent Then
                    cookie.Expires = ticket.Expiration
                End If
                Response.Cookies.Add(cookie)
                Session("login") = Username.Text
                Response.Redirect(FormsAuthentication.GetRedirectUrl(Username.Text, True))
                Exit Select
        End Select

在該代碼母版頁之后:

頁面加載

         If Not Me.Page.User.Identity.IsAuthenticated Then
            Response.Redirect(FormsAuthentication.LoginUrl)
        ElseIf Session("login") = Nothing Then
            FormsAuthentication.SignOut()
            Session.Abandon()
            Session.RemoveAll()
            FormsAuthentication.RedirectToLoginPage("~/default")
        Else
            Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString)
                Using cmd As SqlCommand = New SqlCommand
                    cmd.Connection = con
                    cmd.CommandType = CommandType.Text
                    cmd.CommandText = "select hashtable.Username, lastlogin, hashtable.HASHid, hashtable.compID, company_list.Company_Name from hashtable inner join company_list on company_list.CompanyID = hashtable.CompID where hashtable.username = '" + Session("login") + "'"
                    Dim dt As New DataTable()
                    con.Open()
                    Dim reader As SqlDataReader = cmd.ExecuteReader()
                    dt.Load(reader)
                    userID.Text = "Welcome Mr. " + dt.Rows(0).Item("Username").ToString.Trim()
                    LastLogin.Text = dt.Rows(0).Item("lastlogin").ToString.Trim()
                    Session("Companydetl") = dt.Rows(0).Item("compID").ToString.Trim()
                    Session("lastused") = dt.Rows(0).Item("HASHid").ToString.Trim()
                    con.Close()
                End Using
            End Using
        End If

全球.ASAX

Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        If HttpContext.Current.User IsNot Nothing Then
            If HttpContext.Current.User.Identity.IsAuthenticated Then
                If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
                    Dim id As FormsIdentity = DirectCast(HttpContext.Current.User.Identity, FormsIdentity)
                    Dim ticket As FormsAuthenticationTicket = id.Ticket
                    Dim userData As String = ticket.UserData
                    Dim roles As String() = userData.Split(",")
                    HttpContext.Current.User = New GenericPrincipal(id, roles)
                End If
            End If
        End If
    End Sub

當我在代碼下方運行時,菜單不可見。

<% if (HttpContext.Current.User.IsInRole("Atul")) Then %>
                <a href="/App/core/Company" title="Update Company Details"> Update Company Details</a>
                <% end if %>

當我嘗試了解當前用戶的角色時,它顯示為空白。

請幫忙

首先,在處理用戶輸入時,您應該始終使用參數。 您可以對內部代碼使用字符串連接,但是當輸入來自 web 頁面時,您真的想使用參數。

因此,例如,您的代碼片段應該是這樣的:

另外,請注意 sql 命令 object 有一個連接,有一個閱讀器。 所以很少需要在一個單獨的連接 object 和一個閱讀器上一遍又一遍地編碼——你不需要那些——它們作為 sqlcommand object 的一部分而存在。

例如這個:

    Dim strSQL As String
    strSQL = "select hashtable.Username, lastlogin, hashtable.HASHid, hashtable.compID, company_list.Company_Name from hashtable " &
           "inner join company_list on company_list.CompanyID = hashtable.CompID " &
           "WHERE hashtable.username = @Login"

    Using cmd As SqlCommand = New SqlCommand(strSQL,
                      New SqlConnection(ConfigurationManager.ConnectionStrings("InfinitudeConnectionString").ConnectionString))

        cmd.Parameters.Add("@Login", SqlDbType.NVarChar).Value = Session("login")

        Dim dt As New DataTable()
        cmd.Connection.Open()
        dt.Load(cmd.ExecuteReader)
        With dt.Rows(0)
            userID.Text = "Welcome Mr. " + .Item("Username")
            LastLogin.Text = .Item("lastlogin")
            Session("Companydetl") = .Item("compID")
            Session("lastused") = .Item("HASHid")
        End With

    End Using

所以,請注意我不需要單獨的連接 object,而且我不需要閱讀器(它們已經作為 sql 命令 object 的一部分存在。所以,只是想在這里保存你的鍵盤!!

接下來:

測試/檢查角色成員資格? 如果你正確設置了安全表,那么你應該有這樣的東西:

在此處輸入圖像描述

您真的希望確保您的表格遵循標准 asp.net 安全性。

現在在上面,我的主要聯系人表是自定義的,但表中的 rest 是通過運行 sql 腳本來設置安全性所需和生成的標准表。 這是一筆巨額交易的原因? 然后,您可以通過簡單地進入並在任何子文件夾中擁有 web.config 文件來保護任何 web 頁面,因此您可以保護任何 web 頁面上的基於用戶角色的代碼。

所以,你可以說使用這個:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>

    <authorization>
            <allow roles="PortalMaster" />
        <deny users="*" />
        </authorization>
    </system.web>
</configuration>

那么現在,任何用戶都可以使用具有上述 web 配置的子文件夾中的任何頁面嗎? 他們必須是 PortalMaster 的成員 - 如果他們嘗試加載,他們甚至無法加載該頁面 - 不需要代碼。

如果你做對了,為了測試角色成員資格,那么你可以並且應該使用這個:

  If Roles.IsUserInRole("PortalMaster") then
      ' code goes here for user role = PortalMaster
  End if

所以你可以而且應該能夠使用 Roles.IsUserInRole("some role name")

Dim roles As String() = userData.Split(",")

上面是一個壞主意 - 角色需要來自 Web_usersInRoles 表。

如果您需要顯示給定用戶的所有角色,那么您可以這樣做:

假設我們有一個簡單的按鈕 + 文本框:

   <br />
    <asp:Button ID="Button1" runat="server" Height="34px" Text="Button" Width="170px" />
    <br />
    <asp:TextBox ID="TextBox1" runat="server" Height="188px" TextMode="MultiLine" Width="423px"></asp:TextBox>

按鈕代碼可以是這樣的:

   For Each MyRole As String In Roles.GetRolesForUser()
        TextBox1.Text &= MyRole & vbCrLf
    Next

結果:

在此處輸入圖像描述

使用此設置,然后在母版頁中,您可以控制/設置/隱藏菜單欄項,如下所示:

<li id="mAdmin" runat="server" class="dropdown"  ClientIDMode="Static">

所以上面是一個菜單欄 - 母版頁。 有了角色,我們現在可以這樣做:

 Me.mAdmin.Visible = Roles.IsUserInRole("SiteAdmin")

因此,要在該站點上運行安全性——你真的——但真的真的很想在這里使用並正確設置成員角色表。

因此,要測試角色的成員資格,您可以並且應該能夠使用

Roles.IsUserInRole("some role name here") = true/false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM