| | |
Help with Roles Stored in SQL database
Please support our ASP.NET advertiser: $4.95 a Month - ASP.NET Web Hosting – Click Here!
![]() |
•
•
Join Date: Jun 2005
Posts: 4
Reputation:
Solved Threads: 0
Hi,
I really need some help I've been banging my head again wall with this one.
I have created login page, username and password stored in sql database but now I need to add roles to webpage. Need them to be stored in database because the high amout of users that will be using this webpage.
Just about every example is in C-sharp and I dont have clue how to program in that language, so I had to piece it together with my own code so I need someone's help to look over my code.
I know this post is long.
thanks
Global.asax
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
If Not (HttpContext.Current.User Is Nothing) Then
If HttpContext.Current.User.Identity.IsAuthenticated Then
If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
Dim id As FormsIdentity = CType(HttpContext.Current.User.Identity, FormsIdentity)
Dim ticket As FormsAuthenticationTicket = id.Ticket
Dim userData As String = ticket.UserData
Dim roles As String() = userData.Split("admin")
HttpContext.Current.User = New GenericPrincipal(id, roles)
End If
End If
End If
End Sub
Web.Config
<authentication mode="Forms">
<forms name="MYWEBAPP.ASPXAUTH"
loginUrl="login.aspx"
protection="All"
path="/"/>
</authentication>
<authorization>
<allow users="*"/>
<allow roles="admin" />
</authorization>
Login.aspx.vb
Imports System.Web.Security
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected username As TextBox
Protected Password As TextBox
Protected ErrorLabel As Label
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Sub btnLogin_Click(ByVal sender As Object, ByVal e As EventArgs)
FormsAuthentication.Initialize()
Dim conn As SqlConnection = New SqlConnection("Server=(x);UID=x;Password=x;Database=x") Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "SELECT roles FROM users WHERE username=@username " + "AND password=@password"
cmd.Parameters.Add("@username", username.Text)
cmd.Parameters.Add("@password", Password.Text)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader
If reader.Read Then
Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, username.Text, DateTime.Now, DateTime.Now.AddMinutes(30), True, reader.GetString(0), FormsAuthentication.FormsCookiePath)
Dim hash As String = FormsAuthentication.Encrypt(ticket)
Dim cookie As HttpCookie = New HttpCookie("MYWEBAPP.ASPXAUTH")
If ticket.IsPersistent Then
cookie.Expires = ticket.Expiration
End If
Response.Cookies.Add(cookie)
Dim returnUrl As String = Request.QueryString("ReturnUrl")
If returnUrl Is Nothing Then
returnUrl = "default.aspx"
End If
Response.Redirect(returnUrl)
Else
ErrorLabel.Text = "Username / password incorrect. Please try again."
ErrorLabel.Visible = True
End If
reader.Close()
conn.Close()
End Sub
End Class
Login.aspx
<html>
<head>
<title>Welcome</title>
<script runat="server">
sub Page_Load(Object sender, EventArgs e)
if (User.IsInRole("Admin"))
AdminLink.Visible = true;
end sub
</script>
</head>
<body>
<h2>Welcome</h2>
<p>Welcome, anonymous user, to our web site.</p>
<asp:HyperLink id="AdminLink" runat="server"
Text="Administrators, click here." NavigateUrl="administrators/"/>
</body>
</html>
I really need some help I've been banging my head again wall with this one.
I have created login page, username and password stored in sql database but now I need to add roles to webpage. Need them to be stored in database because the high amout of users that will be using this webpage.
Just about every example is in C-sharp and I dont have clue how to program in that language, so I had to piece it together with my own code so I need someone's help to look over my code.
I know this post is long.
thanks
Global.asax
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
If Not (HttpContext.Current.User Is Nothing) Then
If HttpContext.Current.User.Identity.IsAuthenticated Then
If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
Dim id As FormsIdentity = CType(HttpContext.Current.User.Identity, FormsIdentity)
Dim ticket As FormsAuthenticationTicket = id.Ticket
Dim userData As String = ticket.UserData
Dim roles As String() = userData.Split("admin")
HttpContext.Current.User = New GenericPrincipal(id, roles)
End If
End If
End If
End Sub
Web.Config
<authentication mode="Forms">
<forms name="MYWEBAPP.ASPXAUTH"
loginUrl="login.aspx"
protection="All"
path="/"/>
</authentication>
<authorization>
<allow users="*"/>
<allow roles="admin" />
</authorization>
Login.aspx.vb
Imports System.Web.Security
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected username As TextBox
Protected Password As TextBox
Protected ErrorLabel As Label
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Sub btnLogin_Click(ByVal sender As Object, ByVal e As EventArgs)
FormsAuthentication.Initialize()
Dim conn As SqlConnection = New SqlConnection("Server=(x);UID=x;Password=x;Database=x") Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "SELECT roles FROM users WHERE username=@username " + "AND password=@password"
cmd.Parameters.Add("@username", username.Text)
cmd.Parameters.Add("@password", Password.Text)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader
If reader.Read Then
Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, username.Text, DateTime.Now, DateTime.Now.AddMinutes(30), True, reader.GetString(0), FormsAuthentication.FormsCookiePath)
Dim hash As String = FormsAuthentication.Encrypt(ticket)
Dim cookie As HttpCookie = New HttpCookie("MYWEBAPP.ASPXAUTH")
If ticket.IsPersistent Then
cookie.Expires = ticket.Expiration
End If
Response.Cookies.Add(cookie)
Dim returnUrl As String = Request.QueryString("ReturnUrl")
If returnUrl Is Nothing Then
returnUrl = "default.aspx"
End If
Response.Redirect(returnUrl)
Else
ErrorLabel.Text = "Username / password incorrect. Please try again."
ErrorLabel.Visible = True
End If
reader.Close()
conn.Close()
End Sub
End Class
Login.aspx
<html>
<head>
<title>Welcome</title>
<script runat="server">
sub Page_Load(Object sender, EventArgs e)
if (User.IsInRole("Admin"))
AdminLink.Visible = true;
end sub
</script>
</head>
<body>
<h2>Welcome</h2>
<p>Welcome, anonymous user, to our web site.</p>
<asp:HyperLink id="AdminLink" runat="server"
Text="Administrators, click here." NavigateUrl="administrators/"/>
</body>
</html>
![]() |
Similar Threads
- Update SQL database automatically using VB6 (Visual Basic 4 / 5 / 6)
- SQL Database loop (C#)
- Insert into sql database (ASP.NET)
- SQL Server, Images and DataGrid in ASP.NET (ASP.NET)
- Process very slow - SQL Database (MS SQL)
- Snyc'n Local SQL database online (MS SQL)
Other Threads in the ASP.NET Forum
- Previous Thread: How to get auto calculated expiry date on lost focus event of registration date
- Next Thread: How to compose an html complex email?
| Thread Tools | Search this Thread |
.net 2.0 3.5 activexcontrol ajax alltypeofvideos asp asp.net bc30451 beginner bottomasp.net browser businesslogiclayer c# c#gridviewcolumn cac checkbox class commonfunctions compatible confirmationcodegeneration content contenttype countryselector courier dataaccesslayer database datagrid datagridview datagridviewcheckbox datalist deployment development dgv dropdownlist dropdownmenu dynamic dynamically edit embeddingactivexcontrol fileuploader fill findcontrol flash flv formatdecimal forms formview gridview gudi homeedition iis javascript jquery listbox menu microsoft mouse mssql nameisnotdeclared news opera panelmasterpagebuttoncontrols problem redirect registration relationaldatabases reportemail schoolproject security serializesmo.table sessionvariables silverlight smartcard smoobjects software sql sql-server sqlserver2005 ssl textbox tracking treeview unauthorized validatedate validation vb.net video videos vista visual-studio visualstudio web webapplications webarchitecture webdevelopemnt webdevelopment webprogramming webservice youareanotmemberofthedebuggerusers





