Deny access to a persistent cookie - asp.net

If someone logs in on a pc from Starbucks (for example) and they accidentally check the 'remember me' option thereby setting a persistent cookie on that pc, is there any way of denying that cookie from the server without resorting to changing the cookie name in web.config?

I solved this (a while back actually) by setting a machineKey in web.config & changing it when the username/password is changed:
Sub ChangeMachineKey()
Dim commandLineArgs As String() = System.Environment.GetCommandLineArgs()
Dim decryptionKey As String = CreateMachineKey(64)
Dim validationKey As String = CreateMachineKey(128)
'HttpContext.Current.Response.Write(decryptionKey + "<br />" + validationKey + "<hr />")
Dim filename As String = HttpContext.Current.Server.MapPath("~/Web.config")
Dim XmlReader As XmlTextReader = New XmlTextReader(filename)
Dim xDoc As XmlDocument = New XmlDocument()
xDoc.Load(XmlReader)
XmlReader.Close()
Dim Node As System.Xml.XmlNode = xDoc.SelectSingleNode("//configuration/system.web/machineKey")
Node.Attributes.GetNamedItem("validationKey").Value = validationKey
Node.Attributes.GetNamedItem("decryptionKey").Value = decryptionKey
xDoc.Save(filename)
End Sub
Public Shared Function CreateMachineKey(ByVal numBytes As Integer) As String
Dim Random As Byte() = New Byte(numBytes / 2 - 1) {}
Dim rng As New RNGCryptoServiceProvider()
rng.GetBytes(Random)
Dim machineKey As New System.Text.StringBuilder(numBytes)
Dim i As Integer = 0
Do While i < Random.Length
machineKey.Append(String.Format("{0:X2}", Random(i)))
i += 1
Loop
Return machineKey.ToString()
End Function
This forces everyone to sign in again but since there is only one admin account it works perfectly for me!

Related

Pull Outlook OfficeLocation using Alias

While referencing Return list of names and email address from outlook to vb.net listbox I am trying to fill in a ASP:Textbox with the Office Location of the user.
Currently I pull the current logged in user. The user's username on their PC is also their Outlook Alias. With that being said, I am trying to use the username/Alias to pull the Office location within Outlook. I currently have the following issue with my coding:
'get logged in user(works)
Dim username As String
Dim User As System.Security.Principal.IPrincipal
User = System.Web.HttpContext.Current.User
username = User.Identity.Name.Substring(3)
'Office Location of User
Dim itemx As String
'Create an Outlook application.
Dim oApp As Outlook._Application = New Outlook.Application()
'Get the MAPI namespace.
Dim oNS As Outlook.NameSpace = oApp.Session
'Get the Global Address List.
Dim oALs As Outlook.AddressLists = oNS.AddressLists
Dim oGal As Outlook.AddressList = oALs.Item(1)
'Get all the entries.
Dim oEntries As Outlook.AddressEntries = oGal.AddressEntries
For Each entry In oEntries
If oEntries.GetExchangeUser.Alias = username Then
itemx = oEntries.GetExchangeUser.OfficeLocation
End If
Next
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article in MSDN.
As a workaround you may consider using EWS, see EWS Managed API, EWS, and web services in Exchange for more information. Or just a low-level API on which Outlook is based on - Extended MAPI.
Main thing that I learned was that you need a password and username to access outlook.
Get user ID from PC (Alias for Outlook):
Dim usernameQuery As String
Dim UserQ As System.Security.Principal.IPrincipal
UserQ = System.Web.HttpContext.Current.User
usernameQuery = User.Identity.Name.Substring(3).ToUpper
UserText.Text = usernameQuery
Then:
Call function like so:
'outlook office location **************************************************
LocationText.Text = GetUserInfo(usernameQuery, "physicaldeliveryofficename")
'OTHER OPTIONS YOU CAN QUERY
'Dim svalue As String = GetUserInfo(UserAccount, "mail")
'Dim svalue As String = GetUserInfo(UserAccount, "givenName")
'Dim svalue As String = GetUserInfo(UserAccount, "sn")
'Dim svalue As String = GetUserInfo(UserAccount, "l")
'Dim svalue As String = GetUserInfo(UserAccount, "st")
'Dim svalue As String = GetUserInfo(UserAccount, "streetAddress")
'Dim svalue As String = GetUserInfo(UserAccount, "postalCode")
'Dim svalue As String = GetUserInfo(UserAccount, "telephoneNumber")
'Dim svalue As String = GetUserInfo(useraccount, "co")
'txtName.Text = GetUserInfo(UserAccount, "givenName") & " " & GetUserInfo(UserAccount, "sn")
'txtPhone.Text = GetUserInfo(UserAccount, "telephoneNumber")
'********************************************************************************
Function:
Public Function GetUserInfo(ByVal inSAM As String, ByVal inType As String) As String
Try
Dim sPath As String = "LDAP://"full_path"/DC="path_value",DC="path_value",DC="path_value" "
Dim SamAccount As String = Right(inSAM, Len(inSAM) - InStr(inSAM, "\"))
Dim myDirectory As New DirectoryEntry(sPath, "username", "password") 'pass the user account and password for your Enterprise admin.
Dim mySearcher As New DirectorySearcher(myDirectory)
Dim mySearchResultColl As SearchResultCollection
Dim mySearchResult As SearchResult
Dim myResultPropColl As ResultPropertyCollection
Dim myResultPropValueColl As ResultPropertyValueCollection
'Build LDAP query
mySearcher.Filter = ("(&(objectClass=user)(samaccountname=" & SamAccount & "))")
mySearchResultColl = mySearcher.FindAll()
'I expect only one user from search result
Select Case mySearchResultColl.Count
Case 0
Return "Null"
Exit Function
Case Is > 1
Return "Null"
Exit Function
End Select
'Get the search result from the collection
mySearchResult = mySearchResultColl.Item(0)
''Get the Properites, they contain the usefull info
myResultPropColl = mySearchResult.Properties
If myResultPropColl.Contains(inType) Then
myResultPropValueColl = myResultPropColl.Item(inType)
Return CStr(myResultPropValueColl.Item(0))
End If
'displayname, mail
'Retrieve from the properties collection the display name and email of the user
'myResultPropValueColl = myResultPropColl.Item(inType)
'Return CStr(myResultPropValueColl.Item(0))
Catch ex As System.Exception
End Try
Return "Null"
End Function
FYI-
full_path = "value"."value"."value"

Server Transfer with Session

I have a site contains login page and Default this is part of my code when trying to server transfer from login to Default
Dim userNamePlan As String = UserNameTextBox.Text
Dim PasswordPlan As String = PassWorldTextBox.Text
Dim wrapper As New Simple3Des(MyKey)
Dim userNamePlan As String = UserNameTextBox.Text
Dim PasswordPlan As String = PassWorldTextBox.Text
Dim user As String = wrapper.EncryptData(userNamePlan)
Dim pass As String = wrapper.EncryptData(PasswordPlan)
Session("un") = user.ToString
Session("pw") = PassWorldTextBox.Text
Server.Transfer("Default.aspx")
...
if I change Session("un") = user.ToString to UserNameTextBox.text it will transfer, if not, fail. And no Error Messages. Don't know why
I hope user is already string..Then you can write..
System.Web.HttpContext.Current.Session(“un”)=user;

Asp.Net Identity PasswordHasher not hashing

The following is the code I am using to effect a password change. I am following the pattern in the Manage.aspx page that comes in the Asp>net web application template for changing the password.
Using that method does NOT hash the password, which is odd since the registration DOES hash it. So, i added the passwordhasher. The problem is the IdentityResult is returning false every time even though the three parameters are correct. Every code line produces the correct result until this line, which produces false every time
UPDATE: The usr.ID in the ChangePassword method is the culprit. The username passed in is the ONLY entry in the users table BUT the usr.Id doesn't match the users id in the table. How is it even retrieving an id?
Dim result As IdentityResult = manager.ChangePassword(usr.Id, currentPass, newhash)
Here is the method
Private Sub btnSubmitPasswordChange_Click(sender As Object, e As EventArgs) Handles btnSubmitPasswordChange.Click
Dim db As New MySQLDatabase("MyConnString")
Dim ut As New UserTable(db)
Dim username As String = EncryptDecrypt.DecryptQueryString(Request.QueryString("rtu"))
Dim userId As String = ut.GetUserId(username)
Dim currentPass As String = ut.GetPasswordHash(userId)
Dim usr As New IdentityUser(username)
Dim manager = New UserManager()
manager.UserValidator = New UserValidator(Of IdentityUser)(manager) With {.AllowOnlyAlphanumericUserNames = False}
Dim phasher As New PasswordHasher
Dim newhash As String = phasher.HashPassword(Password.Text)
Dim result As IdentityResult = manager.ChangePassword(usr.Id, currentPass, newhash)
If result.Succeeded Then
Response.Redirect("~/Account/Login.aspx")
Else
lblResetSuccess.Text = "Password change failed!"
End If
Dim changed As Integer = ut.SetPasswordHash(userId, newhash)
End Sub

Get the decrypted content of the section in web.config without saving

How can I get the content of the decrypted webconfig section before it saves the decrypted file: confg.Save()?
Dim confg As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim confgSect As ConfigurationSection = confg.GetSection("section")
If confgSect.SectionInformation.IsProtected Then
confgSect.SectionInformation.UnprotectSection()
confg.Save()
End If
Dim confg As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim confgSect As ConfigurationSection = confg.GetSection("section")
If confgSect.SectionInformation.IsProtected Then
confgSect.SectionInformation.UnprotectSection()
Dim xml As New System.Xml.XmlDocument
Dim node As System.Xml.XmlNodeList
Dim str As String
Dim answer As String
str = confgSect.SectionInformation.GetRawXml()
xml.LoadXml("<ROOT>" + str + "</ROOT>")
node = xml.GetElementsByTagName("TagnameHere")
answer= node(0).Attributes(1).Value
End If
My section in the webcobfig contains multiple tags, so I used xml to get each tag and get its value as an attribute.

How to use ASPxFileManager 'SelectedFiles' property to attach files to MailMessage?

I am using DevExpress tools, specifically the FileManager which has a 'SelectedFiles' property which returns all the data needed to (add,insert,delete,retrieve, modify the record). However I can not figure out how to use the selectedfiles as a MailMessage.Attachment. The code below works to send the email, I've changed the credentials and host values for security. I just need some direction or thought on how to use the FileManager collection that is generated via 'SelectedFiles' and add them as an attachment to the email. I would really like to Zip the files if possible, but at this point simply attaching them is fine. Any thoughts?
Dim fileManager As ASPxFileManager = TryCast(sender, ASPxFileManager)
If ASPxFileManager1.SelectedFiles IsNot Nothing AndAlso ASPxFileManager1.SelectedFiles.Length > 0 Then
For i As Integer = 0 To ASPxFileManager1.SelectedFiles.Length - 1
Dim file = ASPxFileManager1.SelectedFiles.ToString
Dim attachments As New Attachment(fileManager.SelectedFiles.ToString)???
Next
End If
Try
Dim mail As New MailMessage("noreply", DropDownEdit.Text)
Dim smtp_Server As New SmtpClient("host") With {.Credentials = New Net.NetworkCredential("username", "password")}
mail.Subject = "SUBJECT"
mail.IsBodyHtml = False
mail.Body = "Testing"
smtp_Server.Send(mail)
successLabel.Text = "Your email was sent successfully."
Catch ex As Exception
End Try
End Sub
Dim attachments As New Attachment(ReadFile(ASPxFileManager1.SelectedFiles(i)), file)
mail.Attachments.Add(attachments)
The function below was needed to Read the bytes and then attach the items to the MailMessage.
Public Function ReadFile(file__1 As FileManagerFile) As System.IO.Stream
'This function allows us to pull the bytes from the DB value to render the file.
Dim filePath As String = (file__1.RelativeName)
Dim fileData As Byte()
Using con As New SqlConnection([Global].conn)
Dim sqlCmd As New SqlCommand()
sqlCmd.Connection = con
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = file__1.Name
sqlCmd.Parameters.Add("#APIKey", SqlDbType.Int).Value = Session("_UserAPIKey")
sqlCmd.CommandText = "SELECT STATEMENT"
con.Open()
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
If sqlReader.HasRows Then
While sqlReader.Read()
fileData = CType(sqlReader(0), Byte())
End While
End If
End Using
Return New MemoryStream(fileData)
End Function

Resources