Display Message to user and then abandon Session - asp.net

I have added Two Factor Authentication to my Mobile ASP.Net Web App. When the user successfully enters their User Name and Password then a pin number is emailed to their email address which is stored in the database. The issue I am having is that after notifying the user that they don't have an email defined and then reload the login page but my code isn't notifying the user rather it is just reloading the Login.aspx page:
Private Sub GeneratePin()
Dim r As New Random(System.DateTime.Now.Millisecond)
_Pin = CStr(r.Next(1000, 99999))
_email = CIAppGlobals.CurrentUser.UsrContactEmail
With lblPin
.Text = "PIN has been emailed to the you please check your email now."
End With
If Not String.IsNullOrEmpty(_email) Then
Dim Message As String = " Your Mobile PIN number is " & _Pin & vbNewLine & "From IP Address: " & CIAppGlobals.AppSettings.ClientIP
Tools.SendEmail(CIAppGlobals.CurrentUser.UsrContactEmail, "Mobile App - Two Factor Authentication", Message)
Else
Dim sText As String = "Please contact the Administrator You do not have an email address defined within Application."
'DirectCast(HttpContext.Current.Handler, System.Web.UI.Page).ClientScript.RegisterStartupScript(Me.[GetType](), "test", "alert('" & sText & "')", True)
Response.Write("<script>alert('" & sText & "');</script>")
Thread.Sleep(5000)
'Session.Abandon()
'FormsAuthentication.SignOut()
Response.Redirect(ParentFolder & "/Login.aspx")
End If
End Sub

Your call to Response.Redirect() is causing anything you output not to be displayed. You need to remove that, then output a link or some javascript to go to the login page.
Also: you need to remove the call to Thread.Sleep(). That is causing a needless delay and keeping an asp.net thread busy doing nothing. It's not doing what you think it is...

Related

SMTPClient email sometimes going to Junk Mail

I'm having a difficult time understanding why email I send from my website by using SMTP is going to Outlook's junk mail. Here is my code:
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name
Dim split As String() = Nothing
Dim vname As String
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'create the mail message
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress(vname & "#x.com")
mail.To.Add(txtWhoApproves.Text)
'set the content
Dim varstreason, vartxt, vartxt2, varbody As String
varstreason = DropDownList1.SelectedItem.Text
If TextBox1.Text = TextBox2.Text Then
If CheckBox1.Checked = True Then
varbody = TextBox3.Text & " has requested the following time off: " & System.Environment.NewLine & varstreason & " - " & TextBox1.Text & " - All Day"
Else
vartxt = varstreason & " - " & TextBox1.Text
vartxt2 = DropDownList2.SelectedValue & " to " & DropDownList3.SelectedValue
varbody = TextBox3.Text & " has requested the following time off: " & vartxt & " - " & vartxt2
End If
Else
varbody = TextBox3.Text & " has requested the following time off: " & varstreason & " - " & TextBox1.Text & " to " & TextBox2.Text
End If
mail.Subject = "Time Off Approval Requested"
mail.Body = varbody
'send the message
Dim smtp As New SmtpClient("(IP Address of email server)")
'to authenticate we set the username and password properites on the SmtpClient
'smtp.Credentials = New NetworkCredential("username", "secret")
smtp.Send(mail)
I have the email coming from whoever is logged onto the network. Since it's multiple people, I remarked out smtp.Credentials because the password is different for each user (and changes periodically). I'm thinking that this is somehow causing the email to sometimes go into the junk email.
And ideas? How can I prevent these emails from going into junk? We are using an Exchange 2010 server, and Outlook 2007, 2010, or 2013. Thanks in advance!
May be your website is listed as spamming in outlook security systems, or your email contain some spam words or links that causes emails to go in junk or spam box.
Spam filtering for email is based on the content of the subject, message, and attachments. It also filters based on things such as what host/IP you're sending from. If you attempt to send an email via SMTP using a host such as gmail, you'll likely notice it will inbox.
Based on your comments:
The email is coming from your website's SMTP using your domain.
The email is being received by your Exchange server which also uses the same domain.
The emails are only for an internal audience.
From here I would recommend 2 different solutions:
First Solution:
Instead of using your website's SMTP, instead use your Exchange server to send the email. This will work the same as joe#yourcompany.com sending an email to bob#yourcompany.com. The email will never need to leave the server or hit any filters(unless you set up internal filters), so it will not hit the spam box (unless an end user specifically sets it up this way). Check out this site for some help in how to accomplish this: https://www.emailarchitect.net/easendmail/kb/vbnet.aspx
Second Solution:
Use group policies to add the email address to safe senders list for all your users.(https://social.technet.microsoft.com/Forums/office/en-US/c0714d7d-2a42-4b0f-9f1d-63234c7278a0/appending-outlook-safe-senders-list-via-gpo) This seems like it should be an easy solution, but the issue is that it still may not work since you have 2 different servers using the same domain. So although the address may be added in, Outlook may view it as being a different address since it is not coming from the Exchange server. The other option in this solution is to have everyone that gets your email to add it to safe senders directly from the email they receive. That would do it, but hugely inefficient and manual.
For some more in-depth info into the processes and technology behind email, I would recommend checking out the "How Email Works" series of articles by Click-Z (part 1 - https://www.clickz.com/clickz/column/2411041/how-email-works-part-one-the-story-of-send)

Session timed out when POST/GET. Allow login, then post data

Classic asp.
Sometimes the session has timed out while the user has filled out a large form.
Currently the user just gets "you are not logged in", and the login-form.
When the user logs in again, (s)he have to start over, and navigate to the previous form to fill it out again.
I'd like to just submit the formdata again, if the user logs in successfully.
There a many forms/pages in the system, so the login-check is in a common include-file.
Hi Leif Session time is for Server to control the data keeping time , maybe you can use cookie for your issue because it is controlled by Client(Browser). hopefully my idea can help you ,thanks willie
Classic ASP, our "One Way" posting code.
I set a cookie and save the cookie to the members table.
The cookie doesn't need to be anything fancy, date, name, IP, session works just fine. Encode them SHA256 with a Salt.
The idea is to use this special cookie if on a forms page and their user session has been lost or timed out.
Basic setup: (Not complete code just enough to get the idea and flow)
Login page.
Create SHA256 Hash
Save as Cookie
SetKeysCookie "CookieName","LostSession",strSHA256Hash,mysite.ext,"1"
Sub SetKeysCookie(strCookieName,strCookieKey,strCookieValue,strCookieDomain,strCookieExpires)
Response.Cookies(strCookieName).Expires = DateAdd("d",strCookieExpires, Now())
Response.Cookies(strCookieName).Domain = strCookieDomain
Response.Cookies(strCookieName).Path = "/"
Response.Cookies(strCookieName)(strCookieKey) = strCookieValue
Response.Cookies(strCookieName).Secure = True
End Sub
Optional: I use the HTTP_Cookie which would be as follows.
Sub SetKeysCookieHttpOnly(strCookieName,strCookieKey,strCookieValue,strCookieDomain,strCookieExpires)
strGMTDateRFC22 = CookieServerUTC("d","&strCookieExpires&",5,"GMT") ' 1 Day set in char enc dec page
Response.AddHeader "Set-Cookie", strCookieName & "=" & strCookieKey & "=" & strCookieValue & "; expires=" & strGMTDateRFC22 & "; domain="& strCookieDomain &"; path=/;"
End Sub
Update members database:
UPDATE Member SET LostSession='"&strSHA256Hash&"' WHERE ID = "&id&"" .....
On forms page:
Check Session on Post... If Session = NULL then
Check if Cookie is set.
Get the cookie
Old method: Request.Cookies("CookieName")("LostSession")
New HTTP_Cookie
strCookieX = Request.ServerVariables("HTTP_COOKIE")
If InStr(strCookieX,"LostSession=") Then
j = InStrRev(strCookieX, "LostSession=")
if j > 0 Then
strCookieTEMP = Mid(strCookieX, j+12)
end if
j = 64
if j > 0 Then
strCookieTEMP = Left(strCookieTEMP, j-0)
End If
strCookie = strCookieTEMP
End If
The above will pull all your HTTP cookies and then search for your LostSession cookie.
Because we know the fixed length we can pull it cleanly.
Next on the form we check to see which member this cookie is assigned to.
strSQL = "SELECT TOP 1 "
strSQL = strSQL & " ID,Email,ClientID,LostSession"
strSQL = strSQL & " FROM Members "
strSQL = strSQL & " WHERE LostSession = '"&strCookie&"' "
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQL,Conn,3,3
If rs.EOF=False Then
Session("id") = rs("ID")
End If
rs.Close
Set rs = Nothing
When found, we set the minimum Session Variables to allow this post to complete.
Session("id") or Session("authorized") whatever you need to complete the post.
At the end of the post, as we successfully submitted the form we now can send the session failed user to the login page.
Session.Abandon
sRedirectPage = "https://domain.ext/logout.asp"
Response.Status="403.6 IP Restricted"
Response.AddHeader "Location",sRedirectPage
Response.end
You should be able to see the different parts of the http cookie method of saving a session that has timed out.
If you need anything just ask.
Murray
My solution is, in the header file included on all pages, if the user is logged out, create a form with all post and get values hidden, and the username/password field visible.
User then re-enters the username and password, and submits the form.
If the user is then succesfully logged in, the script continues and processes the data.
It will not work for uploads, but this is rarely used anyway.

Cannot send email from godaddy smtp using classic asp - going mad

I am really struggling with something which is pretty basic and need some help as it was not forthcoming from godaddy support!
For some reason the code below is not sending out any emails.
Code seems to be executed property and riddled it with lots of debug msgs but to no helping!
Te "From" email address is valid and has no issues! Any ideas? Port?
cheers, Jay
<%
Dim objNewMail
Set objNewMail = Server.CreateObject("CDO.Message")
objNewMail.From = "info#example.com"
objNewMail.To = "info#example.com"
objNewMail.Subject = "Interesting property sent by xxx"
objNewMail.TextBody = "Click the following link to see the property :" '& vbcr & vbcr & "http://www.maltawide.eu/default.asp?pid="
' GoDaddy SMTP Settings
'I had to remove the smpt settings as I dont have enough rep to post two links!
Response.Write ("Message sent successfully!")
%>
I'm not sure why your message failed, but here is code from a working mail form hosted at GoDaddy. All you need to do is build the form page to submit the form fields used in the script, or change the form field names in the script to match your existing form, or replace the forms with strings. Examples of both form entry and assigned variable values are included in the example's ' Create the message part of the code.
<%
Dim strBody
Dim strToAddress
Dim strFromAddress
Dim strReplyAddress
Dim strBlindCC
' Create the message
strBody = Request.Form("Message")
strToAddress = Request.Form("ToAddress")
strFromAddress = Request.Form("FromAddress")
strReplyAddress = "NoReply#WebSite.com"
strBlindCC = "BlindCC#WebSite.com"
' Include the schemas
sendUrl="http://schemas.microsoft.com/cdo/configuration/sendusing"
smtpUrl="http://schemas.microsoft.com/cdo/configuration/smtpserver"
' Set the mail server configuration
Set objConfig=CreateObject("CDO.Configuration")
objConfig.Fields.Item(sendUrl)=2 ' cdoSendUsingPort
objConfig.Fields.Item(smtpUrl)="relay-hosting.secureserver.net"
objConfig.Fields.Update
' Send the message
Set objMail=CreateObject("CDO.Message")
Set objMail.Configuration=objConfig
objMail.From=strFromAddress
objMail.ReplyTo=strReplyAddress
objMail.To=strToAddress
objMail.BCC=strBlindCC
objMail.Subject=strSubject
objMail.HTMLBody = strBody
objMail.Send
%>

update Master page label with username without pulling from session

On my site I display a logged in username on the master page (in a label) this is done as below, by pulling the username from the session object and putting it into the label on the master page, page_init page event. My problem is that I am bypassing the session now because of timeout issues i wont bore you all with but now I need to change the code to pop the username into the master page label once, then not try and access the session again as it clears after around 10 minutes due to the IIS pool. I realise i could open a new connection to the database each time the master page loaded to retrieve the user name but I thought there might be an easier way than that. any help would be really appreciated.
Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
txtUserInfo.Text = (Session("name") & " [ " & Session("org") & " ]")
End Sub
For the user name alone Humpy's reply would suffice (assuming the thread principal/identity is populated correctly). If you need more bits of information you could use cookies:
After login, set the cookie with a reasonable expiration:
Response.Cookies["userInfo"]["name"] = "currentUsername";
Response.Cookies["userInfo"]["org"] = "currentOrg";
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
On subsequent requests you can pull the data out of the cookie:
if(Request.Cookies["userInfo"] != null)
{
HttpCookie c = Request.Cookies["userInfo"];
txtUserInfo.Text = Server.HtmlEncode(c["name"]) & " [" & Server.HtmlEncode(c["org"]) & "]";
}
See here for more details: http://msdn.microsoft.com/en-us/library/ms178194.ASPX
You should be able to use..
txtUserInfo.Text = User.Identity.Name;
This is how I use mine. Once the user logs in, displays the user's names perfectly. Hope this helps!

How to Make Very Simple ASP.Net Password Protected Page

I am looking for a very simple solution to password protect an ASP.Net page.
I found exactly what I am looking for here but it is in ASP and I do not know the syntax to convert it to ASP.Net.
It simply creates a temporary cookie that will expire as soon as they close their browser window.
I am not looking to store the username / password in a db. I will manually change the password occasionally.
Simply helping me convert the following code to ASP.Net would be wonderful!
This goes on the logon.aspx page and pulls values from a form.
Username="Administrator"
Password="Admin"
Validated = "OK"
if Strcomp(Request.Form("User"),Username,1)=0 AND Request.Form("password") = Password then
Response.Cookies("ValidUser") = Validated
If (Request.QueryString("from")<>"") then
Response.Redirect Request.QueryString("from")
else
Response.Redirect "MyPage.aspx"
End if
Else
If Request.Form("User") <> "" then
Response.Write "<h3>Authorization Failed.</h3>" & "<br>" & _ "Please try again.<br> <br>"
End if
End if
This goes on the password protected page to confirm the cookie was created.
Validated = "OK"
if Request.Cookies("ValidUser") <> Validated then
dim s
s = "http://"
s = s & Request.ServerVariables("HTTP_HOST")
s = s & Request.ServerVariables("URL")
if Request.QueryString.Count > 0 THEN
s = s & "?" & Request.QueryString
end if
Response.Redirect "Logon.aspx"
End if
Just use the built-in forms authentication and setup your credentials store in the web.config.
Here's a quick and dirty example
Another example

Resources