.NET 4.0 FormsAuthentication.SetAuthCookie FAIL - asp.net

I know there are a few questions out there on this already but none seem to help my problem.
I am debugging a VB.NET webForms app and I cannot Get FormsAuthentication.SetAuthCookie to work (with a non-persistent cookie). It seems to create an HttpContext.Current.User object when I check for it in a watch window it seems to have created the object, but not its "Identity" property.
I've read a bunch of SO posts checked the basic things, like seeing if my browser supports cookies, etc... This project is a direct port from an earlier project of ours, which uses the same code for all things listed here, and it works just fine, relatively speaking. Where this throws an exception is where it's called from my BLL code that is supposed to get it.
Here is the code that calls the FormsAuthentication method...:
'When participant logs in having already created records in DB.
Protected Sub btnGo_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnGo.Click
If Me.txtUsername.Text.Trim.Length <> 0 AndAlso Me.txtPassword.Text.Trim.Length <> 0 Then
If Membership.ValidateUser(Me.txtUsername.Text, Me.txtPassword.Text) Then
FormsAuthentication.SetAuthCookie(Me.txtUsername.Text, False)
'This is where we run into trouble; the property checks with the forms auth...
MyBLL.Common.CurrentUser = New MyBLL.User(Me.txtUsername.Text)
'set site property..
If Site_ IsNot Nothing Then
MyBLL.Common.CurrentUser.Site = Me.Site_
End If
MyBLL.Common.CurrentParticpant = Nothing
MyBLL.Common.CurrentParticpantVisitID = -1
Response.Redirect("~/Apps/Dashboard.aspx", True)
Else
Me.lblLoginMsg.Visible = True
End If
Else
Me.lblLoginMsg.Visible = True
End If
End Sub
Here is the code for the BLL object (which has a shared property calling user from HttpContext...)
Public Shared Property CurrentUser() As MyBLL.User
Get
Dim objUser As MyBLL.User
If Not IsNothing(HttpContext.Current.Session("currentSiteUser")) Then
objUser = CType(HttpContext.Current.Session("currentSiteUser"), MyBLL.User)
If objUser.Username <> HttpContext.Current.User.Identity.Name Then
objUser = New MyBLL.User(HttpContext.Current.User.Identity.Name)
HttpContext.Current.Session("currentSiteUser") = objUser
End If
Else
objUser = New MyBLL.User(HttpContext.Current.User.Identity.Name)
HttpContext.Current.Session("currentSiteUser") = objUser
End If
Return objUser
End Get
Set(ByVal value As MyBLL.User)
'_CurrentUser = value
HttpContext.Current.Session("currentSiteUser") = value
End Set
End Property
Here is the Forms element from my webConfig; everything seems alright here to me...
<authentication mode="Forms">
<forms loginUrl="~/Public/Default2.aspx" defaultUrl="~/Public/Default2.aspx" timeout="60"/>
</authentication>

You should immediately redirect after callaing the SetAuthCookie method and only on subsequent requests you may hope to get the full IPrincipal to be initialized. Do not try to access HttpContext.Current.User.Identity.Name in the same controller action in which you called the SetAuthCookie method. It won't have any effect. The redirect is important so that on the next request the forms authentication module will built the principal from the request cookie.
In your CurrentUser method you seem to be calling the HttpContext.Current.User.Identity.Name property but this is not available until you redirect.

Related

"Validation of viewstate MAC failed" only when posting back from a mobile browser that has been idle for sometime

I know that this question has been asked frequently on StackOverflow but my case is a bit different. I checked all the answers related to this issue and none solved my problem as in my case it only happens with browsers on mobile devices.
I only get the "Validation of ViewState MAC failed" error when posting back from a mobile browser that has been left open for some time. The error never appears when submitting a form from a computer browser. It neither appears when submitting from a mobile browser most of the time. It only appears when I open a mobile tab that was already submitted from some time and click the submit button again.
However, It happens all the time as well when I close my browser (so that it is not running in the mobile background), open it again and re-submit the form. I guess this is the main problem behind this error (re-launching the browser is causing page-reload on mobile before clicking on anything).
I tried the below solutions and none of them worked:
Manually set MachineKey to my web.config
Use aspnet_regiis utility to run the managed application where machine keys will be persisted.
Solutions proposed in this article
set LoadUserProfile = True in the application pool
Set the SessionTimeout = 0 in IIS application pool.
Secured my cookies over http.
Note: I know that setting enableViewStateMac="false" in my web.config will solve my problem, but I really don't wish to do so to avoid security depreciation in my application.
After a couple of tests, I noticed that the error only generates when the mobile browser force-reload/relaunch the page. For example, if I re-submit the form that has been already submitted from a mobile, most of the times it does not generate an error. However, sometimes, when I open the browser on the mobile, it force-reload/relaunches the page before I click on anything. Now when I click on the submit button, the error appears.
Possibly, this force-reload/relaunch is causing this error since the ViewState is being altered.
Another possibility is that the mobile is expiring the sessions even though I've set the sessions to not expire in my IIS.
Yet, another possibility would be that the mobile does not allow the browser to run in the background resulting in force-reload to re-construct the page when the user opens the browser again.
I am using the below code in my application:
Partial Class MasterPage
Inherits System.Web.UI.MasterPage
Private Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
Private Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
Private _antiXsrfTokenValue As String
Protected Sub Page_Init(sender As Object, e As EventArgs)
' The code below helps to protect against XSRF attacks
Dim requestCookie = Request.Cookies(AntiXsrfTokenKey)
Dim requestCookieGuidValue As Guid
If requestCookie IsNot Nothing AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue) Then
' Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value
Page.ViewStateUserKey = _antiXsrfTokenValue
Else
' Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N")
Page.ViewStateUserKey = _antiXsrfTokenValue
Dim responseCookie = New HttpCookie(AntiXsrfTokenKey) With {
.HttpOnly = True,
.Value = _antiXsrfTokenValue
}
If FormsAuthentication.RequireSSL AndAlso Request.IsSecureConnection Then
responseCookie.Secure = True
End If
Response.Cookies.[Set](responseCookie)
End If
AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub
Protected Sub master_Page_PreLoad(sender As Object, e As EventArgs)
If Not IsPostBack Then
' Set Anti-XSRF token
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, [String].Empty)
Else
' Validate the Anti-XSRF token
If DirectCast(ViewState(AntiXsrfTokenKey), String) <> _antiXsrfTokenValue OrElse DirectCast(ViewState(AntiXsrfUserNameKey), String) <> (If(Context.User.Identity.Name, [String].Empty)) Then
Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
End If
End If
End Sub
Private Sub MasterPage_Load(sender As Object, e As EventArgs) Handles Me.Load
'Add Base Path and Canonical URL
Dim strBasePath = "<base href='" & AppSettings("LivePath") & "' />"
Page.Header.Controls.Add(New LiteralControl(strBasePath))
End Sub
End Class
I hope there is a solution to this since I don't want to end up setting enableViewStateMac="false" in my web.config
[Update]
Potential Solution:
My current potential solution for this is to handle the "Validation of ViewState MAC failed" error and prompt a custom message to the user explaining the form validation failure. This way security and usability is balanced.
I was inspired by this article for this likely short-lived solution.

How to manitain session values during HttpWebRequest?

In my code I'm sending a HttpWebRequest to a page in my website.
When request sends to this page, It doesn't maintain the Session values.
Below is the code, from where I'm generating the web request:
Public Overloads Shared Function ReadURL(ByVal sUrl As String) As String
Dim sBody As String
Dim oResponse As HttpWebResponse
Dim oRequest As HttpWebRequest
Dim oCookies As New CookieContainer
oRequest = WebRequest.Create("http://localhost:64802/inventory/purchase_order.aspx?id=5654")
oRequest.CookieContainer = oCookies
oResponse = oRequest.GetResponse()
Dim oReader As New StreamReader(oResponse.GetResponseStream())
sBody = oReader.ReadToEnd
oReader.Close()
oResponse.Close()
Return sBody
End Function
Below is the code written on Page_Load of Purchaseorder.aspx.vb:
iDomains_ID = Session("Domains_ID")
iLogin_ID = Session("Login_ID")
sPage = Request.Path
If Request.QueryString.Count > 0 Then sPage &= "?" & Request.QueryString.ToString()
sPage = shared01.Encrypt(sPage, Application("PK"))
If Not User.Identity.IsAuthenticated Or iLogin_ID = 0 Then
Response.Redirect("/login.aspx?page=" & sPage)
Exit Sub
End If
Above code doesn't gets the session values and it redirects to the login page.
So, how i can maintain the session on both pages during HttpWebRequest.
Looking for your replies.
EDIT
I've tried to use CookieContainer class as you can see in above code. But it doesn't work at all.
As an alternative, assuming the calling and called pages are in the same application, you could use the Server.Execute method to load the content of the page without making a separate request to the site:
Public Overloads Function ReadURL(ByVal sUrl As String) As String
Using writer As New StringWriter()
Server.Execute("~/inventory/purchase_order.aspx?id=5654", writer, False)
Return writer.ToString()
End Using
End Function
If I've understood you correctly, you're making a request from one page in your site to another, and you want to send the cookies from the current HttpRequest with your WebRequest?
In that case, you'll need to manually copy the cookies to the CookieContainer:
For Each key As String In Request.Cookies.AllKeys
Dim sourceCookie As HttpCookie = Request.Cookies(key)
Dim destCookie As New Cookie(sourceCookie.Name, sourceCookie.Value, sourceCookie.Path, "localhost")
destCookie.Expires = sourceCookie.Expires
destCookie.HttpOnly = sourceCookie.HttpOnly
destCookie.Secure = sourceCookie.Secure
oCookies.Add(destCookie)
Next
NB: You'll either need to make the ReadUrl function non-Shared, or pass the current HttpRequest as a parameter.
You'll also need to make sure the calling page has EnableSessionState="false" in the <%# Page ... %> directive, otherwise the page you're calling will hang trying to obtain the session lock.
Your code seems like you will need to make a request and a post. The first request will redirect you to your login page. The second will be a request where you post to the login page, which will start the session and (?) store information into the session variables. That post (to the login page) will then redirect you to the page you want.
I used code in this example http://www.codeproject.com/Articles/145122/Fetching-ASP-NET-authenticated-page-with-HTTPWebRe (I tweaked it a bit) to write an application to do this.

SessionID not retaining same value through a session

I have a strnge problem which I dont know how to resolve.
The sessionID keeps changing every time I open a page in the application.
But when I debug the program, the sessionID remains constant and does not change
The application is installed on Windows server 2008 R2 (iis 7.5 and dotnet framework 4.0)
<sessionState cookieless="UseCookies" mode="InProc" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" stateConnectionString="tcpip=127.0.0.1:42424" timeout="60" />
What is the matter?
Note: This works fine on my local development machine.
EDIT
This is the code in Global.asax.vb for Session_Start`
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Session("mySessions") = "junk"
AddMySessions()
If User.Identity.IsAuthenticated Then
Dim cmd As New SqlCommand
Dim sql As String
sql = String.Format("SELECT EmpID FROM Intranet_Employees WHERE Username='{0}'", sUserName)
cmd.CommandText = sql
' Production ...
Session("EmpID") = CType(Dao.ExecuteScalar(cmd, ConfigurationSettings.AppSettings("cSqlTemplateDB")), String)
Dim oEmpInfo As New TOrders.Data.Objects.Employee(Convert.ToInt64(Session("EmpID")))
Session("EmpInfo") = oEmpInfo
If Application("SessionCount") Is Nothing Then
Application.Lock()
Application("SessionCount") = 0
Application.UnLock()
End If
Application.Lock()
Application("SessionCount") += 1
Application.UnLock()
Else
Response.Redirect("http://intranet/tsystem")
End If
End Sub
Private Sub AddMySessions()
Dim sMsg As String = Session.SessionID & ";" & Now.ToString & ";" & Request.ServerVariables.Get("AUTH_USER").ToString
If IsNothing(Application("mySessions")) Then
Dim arrSessions As New ArrayList
arrSessions.Add(sMsg)
Application.UnLock()
Application("mySessions") = arrSessions
Application.Lock()
arrSessions = Nothing
Else
Dim arrTemp As ArrayList = CType(Application("mySessions"), ArrayList)
arrTemp.Add(sMsg)
Application.UnLock()
Application("mySessions") = arrTemp
Application.Lock()
arrTemp = Nothing
End If
sMsg = Nothing
End Sub
`
From MSDN:
When using cookie-based session state, ASP.NET does not allocate
storage for session data until the Session object is used. As a
result, a new session ID is generated for each page request until the
session object is accessed. If your application requires a static
session ID for the entire session, you can either implement the
Session_Start method in the application's Global.asax file and store
data in the Session object to fix the session ID, or you can use code
in another part of your application to explicitly store data in the
Session object.
If your application uses cookieless session state, the session ID is
generated on the first page view and is maintained for the entire
session.
After more than week of frustration, I finally figured it out. The issue was not with the code or web.config - but with the naming of the Server. The server name contained the underscore '_' which was blocking cookies. The server name was changed and everything worked fine.
#fnostro - Thanks for your patience and suggestions.
Here is the link from microsoft.
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q316112

Can I modify the Request.Headers collection?

I have an ASP.NET site that uses a third-party reporting component. This component is misbehaving by throwing a NullReferenceException whenever the client browser is not specifying a User-Agent in the request headers.
It's basically an odd scenario that I'm just trying to come up with a workaround for. I do not know who/what client is not specifying a User-Agent, which seems like bad form IMO, but we have to deal with the exceptions it is generating. I have logged a support ticket with the third-party regarding the bug in their reporting component, but I have my doubts about how fruitful that route is going to be. So my thought was just to detect when the User-Agent is blank and default it to something just to appease the reporting component. However, I can't seem to change anything in the Request.Headers collection. I get the following exception:
Operation is not supported on this platform.
I'm starting to believe I'm not going to be able to do this. I understand why ASP.NET wouldn't allow this, but I haven't come up with any other workaround.
Update: At penfold's suggestion, I tried to add the User-Agent to the Request.Headers collection using an HttpModule. This got it added to the Headers collection, but did nothing to update the Request.UserAgent property, which is what is causing the reporting component to fail. I've been looking through .NET Reflector to determine how that property is set so that I can update it, but I haven't come up with anything yet (there isn't just a private field that drives the property that I can find).
Recently I also facing similar problem same as you. I overcome the problem
of Request.UserAgent by using a mock HttpWorkerRequest.
(Assuming you already solve the agent string in Request.Headers with custom HttpModule)
Here is the sample code:
Friend Class MockedRequestWorker
Inherits HttpWorkerRequest
Private ReadOnly _BaseHttpWorkerRequest As HttpWorkerRequest
Private ReadOnly _UserAgent As String
Friend Sub New(ByVal base As HttpWorkerRequest,
ByVal UserAgent As String)
_BaseHttpWorkerRequest = base
_UserAgent = UserAgent
End Sub
Public Overrides Sub EndOfRequest()
_BaseHttpWorkerRequest.EndOfRequest()
End Sub
Public Overrides Sub FlushResponse(ByVal finalFlush As Boolean)
_BaseHttpWorkerRequest.FlushResponse(finalFlush)
End Sub
'Note: remember to override all other virtual functions by direct invoke functions
'from _BaseHttpWorkerRequest, except the following function
Public Overrides Function GetKnownRequestHeader(ByVal index As Integer) As String
'if user is requesting the user agent value, we return the
'override user agent string
If index = HttpWorkerRequest.HeaderUserAgent Then
Return _UserAgent
End If
Return _BaseHttpWorkerRequest.GetKnownRequestHeader(index)
End Function
End Class
then, in your custom HttpApplication.BeginRequest handler, do this
Private Sub BeginRequestHandler(ByVal sender As Object, ByVal e As EventArgs)
Dim request As HttpRequest = HttpRequest.Current.Request
Dim HttpRequest_wrField As FieldInfo = GetType(HttpRequest).GetField("_wr", BindingFlags.Instance Or BindingFlags.NonPublic)
Dim ua As String = "your agent string here"
Dim _wr As HttpWorkerRequest = HttpRequest_wrField.GetValue(request)
Dim mock As New MockedRequestWorker(_wr, ua)
'Replace the internal field with our mocked instance
HttpRequest_wrField.SetValue(request, mock)
End Sub
Note: this method still does not replace the user agent value in ServerVariables, but it should able to solve what you need(and my problem too)
Hope this help :)
protected void Application_BeginRequest(Object sender, EventArgs e) {
const string ua = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
Request.Headers["User-Agent"] = ua;
var httpWorkerRequestField = Request.GetType().GetField("_wr", BindingFlags.Instance | BindingFlags.NonPublic);
if (httpWorkerRequestField != null) {
var httpWorkerRequest = httpWorkerRequestField.GetValue(Request);
var knownRequestHeadersField = httpWorkerRequest.GetType().GetField("_knownRequestHeaders", BindingFlags.Instance | BindingFlags.NonPublic);
if (knownRequestHeadersField != null) {
string[] knownRequestHeaders = (string[])knownRequestHeadersField.GetValue(httpWorkerRequest);
knownRequestHeaders[39] = ua;
}
}
}
I think the best way of handling this is to use a http module that will check the header and inject the user agent if necessary.
As you have found out you cannot use the set method on the Headers object. Instead you will have to inject the user agent string into the header via protected properties that can be accessed through reflection as outlined in the answer to this question.
UPDATE
Unfortunately Request.UserAgent doesn't use the information held in Request.Headers, instead it calls the method GetKnownRequestHeader in HttpWorkerRequest. This is an abstract class and from looking at the decompiled library code the actual implementation varies depending on the hosting environment. Therefore I cannot see a way to replace the user agent string in a reliable manner via reflection. You could roll your own WorkerRequest class but for the amount of effort I don't think the payoff would be worth it.
Sorry to be negative but I think its just not possible to set the user agent within the web application in a simple manner. Your best option at the moment would be to perform a pre-check for a user agent, and if the request doesn't have one return a browser not supported error message.
You could also investigate injecting something earlier on, i.e. in IIS or at your proxy server if you use one.
Also I would recommend that this issue is reported to SAP. I know they are actively working on the Viewer at the moment and who knows they might fix it and maybe even add support for Opera!

ASP.NET Is it possible to handle all the null session checking in masterpage

I have the following steps in my webpage
1) User Logs in and I set the following session variables
Session("userName") = reader_login("useremail").ToString()
Session("userId") = reader_login("user_ID").ToString()
Session("firstName") = reader_login("firstName").ToString()
2) Now on my logged in VB.NET templates I reference a MasterPage called LoggedIn.Master. In Which I added the following method to check for the above null session variables. And if they null to redirect back to login page.
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
'#Check that User is Logged in, if not redirect to login page
If (Session("userId") Is Nothing) Or (Session("userName") Is Nothing) Or (Session("firstName") Is Nothing) Then
Response.Redirect(ConfigurationManager.AppSettings("site_base_url").ToString & "login/", False)
End If
3) Now my question is if I want to use any above 3 Session variables in different .net templates or usercontrols referencing the above master page do i need to AGAIN add the check
If (Session("userId") Is Nothing) Or (Session("userName") Is Nothing) Or (Session("firstName") Is Nothing) Then
Response.Redirect(ConfigurationManager.AppSettings("site_base_url").ToString & "login/", False)
End If
In the respective pages or will the check in master page do. Because at the moment i.e. if in a usercontrol I attempt to do i.e.
customerName.Text = Session("userName").ToString()
or
Response.Write(Session("userName").ToString())
I am getting the error
Object reference not set to an instance of an object.
customerName.Text = Session("userName").ToString()
You can write a wrapper around the Session to handle null values and just call the wrapper when you access the items:
Public Class SessionWrapper
Public Shared ReadOnly Property Item()
'Access session here and check for nothing
End Property
End Class
And use it like this
SessionWrapper.Item("itemName")
In answer to your question - as long as the masterpage checks the session and redirects before all your controls and page code make a reference to Session, you should be fine.
You were using OnInit() which seems reasonable, but see this article for a good understanding of the timing of events.
Incidentally, I strongly discourage the use of ad-hoc calls to Session in your page and control code. Instead, I recommend you create a static SessionManager class that does the Session referencing for you. That way, you get to benefit from strong typing, and won't be able to accidentally make hard-to-debug 'session key' typos in your code like Session["FiirstName"]. Also, you can incorporate your null-session check right into the call for the session value:
EXAMPLE (in C#, sorry!)
public static class SessionManager
{
private static void EnsureUserId()
{
if (Session["userId"] == null)
{
Response.Redirect("YourLogin.aspx", false);
}
}
public static string FirstName
{
get
{
EnsureUserId();
if (Session["firstName"] == null)
Session["firstName"] = "";
return (string)Session["firstName"];
}
set
{
Session["firstName"] = value;
}
}
}
You can create an http module that asks about the session objects and if they are null, it will redirect to the login page and by developing this http module, in each page request the module will do the check and then you can use it normally without checking.
A better way to handle this would be to add a base class for all controls that require this session variables to be present. You can then add properties to wrap access to the session and other cool stuff and the check will work even if the controls are used with a different master page.

Resources