i have a project where i need to use the active directory for login to a website made in asp.net, i follow this tutorial....
Active Directory Authentication from ASP .NET
now i want to get the groups of the user, i tried the next code in the default.aspx.vb page but doesn't work..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write("Hello, " + Server.HtmlEncode(User.Identity.Name))
Dim id As FormsIdentity = CType(User.Identity, FormsIdentity)
If id IsNot Nothing Then
Dim ticket As FormsAuthenticationTicket = id.Ticket
Response.Write("<p/>TicketName: " + ticket.Name)
Response.Write("<br/>Cookie Path: " + ticket.CookiePath)
Response.Write("<br/>Ticket Expiration: " + ticket.Expiration.ToString())
Response.Write("<br/>Expired: " + ticket.Expired.ToString())
Response.Write("<br/>Persistent: " + ticket.IsPersistent.ToString())
Response.Write("<br/>IssueDate: " + ticket.IssueDate.ToString())
Response.Write("<br/>UserData: " + ticket.UserData)
Response.Write("<br/>Version: " + ticket.Version.ToString())
End If
End Sub
I find a better solution, is more easy than any answer that i find on the internet.
First i create a class to validate if an user is in a group in the active directory:
Imports System.Security.Principal
Public Class AutorizationFun
Dim access As Boolean = False
Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
Public User As WindowsPrincipal = New WindowsPrincipal(id)
Region "Groups Verification"
'Belongs to sample group
Private Function inSampleGroup() As Boolean
Return User.IsInRole("bth0\GG BTUC-SAMPLEGROUP")
End Function
Private Function inSampleGroup2() As Boolean
Return User.IsInRole("bth0\GG BTUC-SAMPLEGROUP2")
End Function
End Region
Public Function ProgramsAccsess(ByVal vPage As String) As Boolean
access = False
Select Case vPage
Case "~/Sample.aspx"
If inSampleGroup() Then
access = True
End If
'---------------------------------------------------------------------
End Select
'*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
'access = True
'*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Return access
End Function
End Class
Then you have to create a function in the code behind of all pages:
'create var
Dim ValidateUser As New AutorizationFun
Protected Sub VerifyAccessPage()
If ValidateUser.ProgramsAccsess(Request.AppRelativeCurrentExecutionFilePath) = False Then
Response.Redirect("~/DeniedAccess.aspx")
End If
End Sub
And to finish to have to use the function in the Page_load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'check whether page is postback or not
If Not Page.IsPostBack Then
VerifyAccessPage()
End If
End Sub
If your server is in a Windows Domain it should be connected to Active Directory, so by using windows authentication you already login with AD credentials (since the user has to be in the domain before, or it will be asked for AD credentials by the browser)
To get the user groups you could use the DirectorySearcher class, obviously when you
Related
When I open a page from another web application on same domain I am trying to read the cookie that was created on the original page, But it I cant read the cookie. If I move that page in to the same web application then it works, but thats not what I want.
[Domain: MyCompany.mobi]
[WebApp A] - create cookie and launch page
Protected Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim aCookie As New HttpCookie("TestCookie")
aCookie.Value = "Hello World"
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)
Dim script = "window.open('http://MyCompany.mobi/webappB/default.aspx?id=TestCookie')"
'open page in WebsiteB
ScriptManager.RegisterStartupScript(Me, Me.GetType, "OpenPage", script, True)
End Sub
[Domain: MyCompany.mobi]
[WebApp B] - read the cookie and display in label
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim id As String = ""
If Request.QueryString("id") IsNot Nothing Then id = Request.QueryString("id").ToString
If Request.Cookies(id) IsNot Nothing Then
Dim aCookie As HttpCookie = Request.Cookies(id)
Label1.Text = aCookie.Name & " : " & aCookie.Value
Else
Label1.Text = "Cannot read cookie"
End If
End Sub
Cookies are associated with domain names; not the physical servers that are pointed to by DNS.
For security reasons, you cannot read cookies from a different domain name.
You need to pass the information in the URL.
i have ASP.NET page, its code-behind, and a Class file:
Folder1/page.aspx (asp.net page), it contains a label:
<asp:Label runat="server" ID="Label1" Visible="false"></asp:Label>
Folder1/page.aspx.vb (code-behind), it calls connection.vb like this:
Dim x As New Connection
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
x.checkusernameExists(TextBoxUsername.Text)
' I try to access `Boolean variable` Flag from Class file but I can't.
End Sub
App_Code/connection.vb (a class file that i created):
Public Class Connection
Public Sub checkusernameExists(ByVal username1 As String)
Dim flag as Boolean
' I try to access here `Label1.text` & `Label1.visible` to work on it but I can't.
End Sub
End Class
My Questions
1 - How can I access the Label1 from the ASP.NET page in Connection.vb?
2 - How can I access the Boolean variable from Connection.vb in page.aspx.vb (code behind)?
I am really stuck in this.
Thank you.
Use (public) properties or method parameters.
You have to ask yourself following: why should a class that is responsible for a connection(i assume to database) have access to your GUI at all? Don't hardlink different layers with each other, otherwise you won't be able to use them alone.
I would suggest to let the connection class do it's work and that is not to modify your frontend. Instead the controller (the aspx page) should manage it's GUI and call the connection class, using the return value to determine what to do next with the Label.
So return a Boolean to indicate if the user is valid:
Public Class Connection
Public Shared Function checkusernameExists(ByVal username1 As String)As Boolean
Dim userExists As Boolean
' acces db to check if the username exists '
Return userExists
End Sub
End Class
in your page:
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
Dim userExists As Boolean = Connection.checkusernameExists(TextBoxUsername.Text)
Label1.Visible = userExists
If Label1.Visible Then Label1.Text = "Hello again " & TextBoxUsername.Text
End Sub
make flag as property and set this property in checkusernameExists function
Public Class Connection
Public Property Flag as Boolean
Public Sub checkusernameExists(ByVal username1 As String)
// set flag here
Flag = True // or whateever value returned from the database
' I try to access here `Label1.text` & `Label1.visible` to work on it but I can't.
End Sub
End Class
and access this instance level property in page.aspx.vb file
Dim x As New Connection
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
x.checkusernameExists(TextBoxUsername.Text)
Label1.Visible= x.Flag;
' I try to access `Boolean variable` Flag from Class file but I can't.
End Sub
You can use Function to return value and pass label as parameter.
Public Function SaveChanges(ByRef Label1 As Label, ByVal username1 As String) As Boolean
{
Return True
}
It would be better if you pass the label properties to function instead of passing the object of label as it couple up two classes.
I'm trying to get thee previous page visited in ASP.NET using VB.NET using the following code:
Partial Class _Default Inherits Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim previousPage As String = Page.Request.UrlReferrer.ToString
If (Request.UrlReferrer <> Nothing) Then
If previousPage.Contains("Login") Then
Dim tUsername As String = Session("Username")
lblUsername.Text = "Welcome, " + tUsername
ElseIf previousPage.Contains("Register") Then
Dim cUsername As String = Session("CUsername")
lblUsername.Text = "Welcome, " + cUsername
Else
lblUsername.Text = "Welcome, Guest"
End If
End If
End Sub
End Class
I get this error:
Object reference not set to an instance of an object.
at:
Dim previousPage As String = Page.Request.UrlReferrer.ToString
What I want to do is get the previous page visited so I can get a session variable.
Try This code.
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If (Request.UrlReferrer <> Nothing) Then
Dim previousPage As String = Page.Request.UrlReferrer.ToString
If previousPage.Contains("Login") Then
Dim tUsername As String = Session("Username")
lblUsername.Text = "Welcome, " + tUsername
ElseIf previousPage.Contains("Register") Then
Dim cUsername As String = Session("CUsername")
lblUsername.Text = "Welcome, " + cUsername
End If
Else
lblUsername.Text = "Welcome, Guest"
End If
End Sub
End Class
Unsure what you are trying to do but while its easy enough to answer your specific question, you should take a step back and review why you are doing things that way.
It seems you are trying to control flow based on some authentication. If so, consider ASP.Net Forms Authentication +/- Login Controls. You can "plug" this architecture into your existing auth mechanism (meaning you don't have to uproot your existing stuff to implement it).
(If you still want to reinvent the wheel) Consider cookies instead of trying to figure out "where the user came from" prior to landing on "this" page - both of which can vary by x - the more web pages your web site has or will have, you'll have more spaghetti.
i need to retrive some data from table registration of database to show.aspx page after login. when i register a new user after registration and redirect it to the profile.aspx page then it works fine(showing all required data). but if i do logout and again do login to the same user then the page show.aspx show nothing
I am using this code for user login:
Protected Sub btnLogin_Click1(ByVal sender As Object, ByVal e As System.EventArgs)
Dim admin As String = "Admin"
Dim objcmd As New SqlCommand(("select * from Login where UserName='" + txtUserName1.Text & "' And Password='") + txtPassword1.Text & "'", con)
Dim objReader As SqlDataReader
con.Open()
objReader = objcmd.ExecuteReader()
If objReader.HasRows Then
While objReader.Read()
If [String].Compare(objReader("UserType").ToString(), admin) = 0 Then
Session("UserName_Admin") = txtUserName.Text.ToString().Trim()
Session("UserName") = txtUserName.Text.ToString().Trim()
Response.Redirect("adminview.aspx")
Else
Session("UserName") = txtUserName.Text.ToString().Trim()
Response.Redirect("show.aspx")
End If
End While
Else
lblLoginMessage.Text = "Login failed. Please try again"
End If
con.Close()
End Sub
code in the show.aspx page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Session("UserName") Is Nothing Then
Response.Redirect("registration.aspx")
End If
binddata()
End Sub
Sub binddata()
Dim mycommand As New SqlCommand("SELECT * FROM registration where UserName = #UserName", con)
mycommand.Parameters.AddWithValue("#UserName", Session("UserName").ToString())
con.Open()
ProfileData.DataSource = mycommand.ExecuteReader
ProfileData.DataBind()
con.Close()
End Sub
Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Redirect("upimg.aspx")
End Sub
i am using a datalist to retrieve data from database in show.aspx page.
is there anything i need to change in web.config file . a help will be appreciated
Is your logout code clearing the session values?
I think you would be far better off using the ASP.net Membership and Roles to handle this functionality because it will be much more secure and flexible.
Check out here an article explaining how to get setup here
I completely agree with #John Mc, using the Membership provider would be a much better idea.
As to clearing out session info, you should use:
Session.Clear()
Session.Abandon()
I'm using ASP.net 4.0 VB :)
I am using a session variable to add a user entered code into the url of each page. I can get the code to show up at the end of the page's URL that my textbox is on, but what do I add to every page to make sure that the session stays at the end of every URL that person visits during their session? This is the code from the page that the user enters their user code.
Protected Sub IBTextBoxButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles IBTextBoxButton.Click
Session("IB") = IBTextBox.Text
Dim IB As String = Session("IB")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ProductID.Value = Request.QueryString("id")
If Session("IB") Is Nothing Then
tab4.Visible = "False"
Else
tab4.Visible = "True"
End If
End Sub
This is what I have in the page load of one of the other pages. What else do I add to make sure that variable is added to the URL of that page?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim IB As String
IB = Session("IB")
End Sub
string url = Request.Url.ToString();
string newUrl = url + url.Contains("?") ? "&" : "?" + "ib=" + Server.UrlEncode(IBTextBox.Text);
Response.Redirect(newUrl);
return;
The approach I might use would be to create a base page class that all of your pages can inherit. The base page would then inherit the System.Web.UI.Page.
Within your base page class, create a property for IB and also handle the page load event.
In that event, check if the QueryString has the IB parameter in it. If it does, set the property to the value in the parameter.
Private _IB As String
Public Property IB() As String
Get
Return _IB
End Get
Set(ByVal value As String)
_IB = value
End Set
End Property
Public Function GetIB(ByVal url As String) As String
If Not(_IB = String.Empty) Then
If (url.Contains("?")) Then
Return "&IB=" & _IB
Else
Return url & "?IB=" & _IB
End If
Else
Return url
End If
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (String.IsNullOrEmpty(Request.QueryString("IB"))) Then
_IB = Request.QueryString("IB")
End If
End Sub
Finally in your markup you would need to place something like the following at the end of all of your links:
next page
I threw this code into the Master Page to make sure that every page knows whether or not the Session is there. Thanks for all the help everyone!
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Session("IB") Is Nothing Then
IBText.Visible = True
IBTextBox.Visible = True
IBTextBoxButton.Visible = True
Else
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name")
End If
End Sub