Object Passing through Session in webforms asp.net - user-profile

I am working on asp.net webforms. There's is a user login page if user successfully login then it saves all the data in object of class profile data after accessing through sql database
Profiledata profiledata = new Profiledata();
profiledata.Fname = SelectReader.GetString(0);
profiledata.Lname = SelectReader.GetString(1);
profiledata.email = SelectReader.GetString(2);
profiledata.password = SelectReader.GetString(3);
\\if we print profiledata values here all values are shown correct
Session["profile"] = profiledata;
On the next page I am accessing
Profiledata profiledata = new Profiledata();
profiledata = (Profiledata)Session["profile"];
but it shows null exception in Session no value found in session

If you are retrieving session value before session is filled, it can be null.
It can be null also if you have disabled the SessionState http module or if your code runs in a HttpHandler, that does not specify either the IRequiresSessionState or IReadOnlySessionState

Related

how to prevent user login with same account in ASP.NET MVC

I want to prevent multiple login for user with same username and password . Example :
User A login with account "A", Session["AccountA"] is create ( about 30 minutes ) . After user B login with account "A" ,Session["AccountA"] is create and Session["AccountA"] of user A timeout .
Yes, it is possible (although may not be as great an idea as you are thinking). Here's one way to do it:
When the user signs on, store a value in Application state that binds his session ID to his user ID.
var context = HttpContext.Current;
var lookup = String.Format("Session_{0}", userID);
Application.Lock();
Application[lookup] = context.Session.SessionID;
Application.Unlock();
When a user requests a page (and is not signing on) check to see if the binding is correct. If not, kill the session.
var context = HttpContext.Current;
var lookup = String.Format("Session_{0}", userID);
var sessionID = Application[lookup] as string;
if (sessionID != context.Session.SessionID)
{
context.Session.Abandon();
var c = new HttpCookie(FormsAuthentication.FormsCookieName,"DELETED");
c.Expires = System.DateTime.Now.AddDays(-2);
context.Response.AppendCookie(c);
context.Response.Redirect("~/logout.aspx");
}
When a user attempts to access a page, but has the wrong session ID, his session will be killed.
The trick here is... your Application state will keep growing as users sign on. You will need to devise some means of detecting when users have signed off and cleaning it up, or you will need to recycle your AppPool on a regular basis.

WebUserControl changes to Viewstate are not accessible at page level

I'm developing an ASP.NET Webforms application and while using the WebUserControl I stumbled upon a behavior I dont understand.
My WebUserControl puts 4 strings into the ViewState:
var projectCode = SelectedProject.Value;
ViewState["ProjectCode"] = projectCode;
var resourceId = SelectedResource.Value;
ViewState["ResourceCode"] = resourceId;
var indicatorId = SelectedIndicator.Value;
ViewState["IndicatorCode"] = indicatorId;
var areaCode = SelectedArea.Value;
ViewState["AreaCode"] = areaCode;
When thats done, my page should get these values from the ViewState, but the ViewState does not contain any items and returns null for all 4 keys.
Why is the ViewState on the page level empty? And if I shouldn't use the ViewState for this, whats the best method to pass values forth and back?
Because the keys you are using are local for the current usercontrol: the "AreaCode" defined in the viewstate for the UserControl is not the same as the one defined for the page.
This behaviour is different from the Session one.
You can use the Session dictionary or implement some public methods on your user control to retrieve the values.

I can't read cookies in master or other pages

I create some cookies in logon.aspx.cscodebehind thatc read and contain user info from DB with data reader .
HttpCookie UID = new HttpCookie("ID");
Response.Cookies["UID"].Value = Recordset[0].ToString();
Response.Cookies.Add(UID);
HttpCookie UName = new HttpCookie("Username");
Response.Cookies["Username"].Value = Recordset[3].ToString();
Response.Cookies.Add(UName);
HttpCookie Pass = new HttpCookie("Pass");
Response.Cookies["Pass"].Value = Recordset[4].ToString();
Response.Cookies.Add(Pass);
HttpCookie Admins = new HttpCookie("Admin");
Response.Cookies["Admin"].Value = Recordset[12].ToString();
Response.Cookies.Add(Admins);
HttpCookie Mails = new HttpCookie("Emails");
Response.Cookies["Emails"].Value = Recordset[9].ToString();
Response.Cookies.Add(Mails);
Response.Redirect("../default.aspx");
when i trace the code every thing is good and data hold by cookies.
Now when i read these cookies in master page or other content page, i can't.
in other worlds the cookies not recognize by their names(or keys)
if (Request.Cookies["Username"] !=null)
{
lblWelcomeUser.Text = Server.HtmlEncode(Request.Cookies["Username"].Value);
pnlUsersNavigation.Visible = true;
LoginMenu.Visible = false;
RegisterMenu.Visible = false;
lblWelcomeUser.Text = Server.HtmlEncode(Request.Cookies["Username"].Value);
//lblWelcomeUser.Text = Request.Cookies["Username"].Value.ToString();
if (Request.Cookies["Admin"].Value.ToString()=="True")
{
lblWelcomeUser.Text = "WELCOME ADMIN";
// Show Menu that is only for Admin
}
where is the problem in this code?
It appears that you might be overwriting the cookie with a good value, with a new empty cookie.
// new cookie created - empty
HttpCookie UName = new HttpCookie("Username");
// new cookie created with a value
Response.Cookies["Username"].Value = Recordset[3].ToString();
// overwrite new cookie with value with new empty cookie
Response.Cookies.Add(UName);
Create the cookie, set the value, then add the cookie to the response.
HttpCookie UName = new HttpCookie("Username");
UName.Value = Recordset[3].ToString();
Response.Cookies.Add(UName);
Also note that as Paul Grimshaw pointed out, you can add multiple values to the same cookie.
Download Fiddler to check request/response to ensure your cookies contain the correct values and such... http://fiddler2.com/get-fiddler
Also be careful about Man-in-the-middle attacks. Storing usernames and passwords in plain text is not such a good idea to begin with.
This doesn't look like a very secure way of securing access to your application. Try looking at ASP.NET membership.
Otherwise try setting an expiry date. Also, as this example shows, you may want to store all the above info in one cookie:
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["UID"] = Recordset[0].ToString();
myCookie["Username"] = Recordset[3].ToString();
//...etc...
myCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(myCookie);
Also, from MSDN:
By default, cookies are shared by all pages that are in the same
domain, but you can limit cookies to specific subfolders in a Web site
by setting their Path property. To allow a cookie to be retrieved by
all pages in all folders of your application, set it from a page that
is in the root folder of your application and do not set the Path
property. If you do not specify an expiration limit for the cookie,
the cookie is not persisted to the client computer and it expires when
the user session expires. Cookies can store values only of type
String. You must convert any non-string values to strings before you
can store them in a cookie. For many data types, calling the ToString
method is sufficient. For more information, see the ToString method
for the data type you wish to persist.

Does the Facebook C# SDK depend on cookies on the server?

I'm using the Facebook C# SDK and am trying to figure out exactly how it works. I actually use an AJAX web method to lookup the Facebook account details based on the authenticated user ID, which looks something like this:
if (response.status === "connected")
{
KitchenPC.LogonFB(response.authResponse.userID, checkResult, facebookError);
}
On the server side, the LogonFB web method does something like:
Client = new FacebookClient(applicationId, applicationSecret);
var result = Client.Get(path) as IDictionary<string, object>;
UserId = Int64.Parse((String)result["id"]);
Name = result["name"] as String;
FirstName = result["first_name"] as String;
LastName = result["last_name"] as String;
Location = result.ContainsKey("location") ? result["location"] as String : "";
Gender = result.ContainsKey("gender") ? result["gender"] as String : "";
Email = result["email"] as String;
Where path is the user ID passed in from the client.
My Question:
I'm switching from ASP.NET Web Service to WCF, and WCF does not support cookies. In fact, HttpContext.Current will be null within the WCF pipeline. I was under the impression that the Facebook C# SDK depended on the fbm_ and fmsr_ cookies being passed in on the request, which would be used to validate the session with the Facebook server. However, much to my surprise, the .Get() call still works, and user information is returned. I also dug through the SDK source code and nowhere in it do I find references to HttpContext.Current.
Does the Facebook C# SDK work completely independently of cookies? Does this mean that all I need is the user's Facebook ID, and as long as they've previously approved my app ID, I can grab information about their account?
I just want to make sure I'm not doing anything wrong, and I'm not going to run into trouble in production.
When you pass the constructor with appId and appSecret, it will auto set the access token as app access token using string.Concat(appId, '|', appSecret). That constructor has been removed in newer version of the sdk. https://github.com/facebook-csharp-sdk/facebook-csharp-sdk/issues/103
Set it to null if you don't want the access token.
Client = new FacebookClient(applicationId, applicationSecret);
Client.AccessToken = null;
var result = Client.Get(path) as IDictionary<string, object>;

Newly Created Session doesn't retain session contents

The system I am working on does not use standard ASP.NET Auth/ Membership facilities for logging users in/ out. Therefore after logging the user in I want to issue a new Session ID to the user in order to prevent Session trapping/ Hijacking. The problem i have is that although I have been able to successfully create a new session with a new ID and copy the various components to the newly created session eg. session["value"]. By the end of the code excerpt below the newly created session is the current HTTPContext's session, and has the session values that were copied accross. However after performing a Response.Redirect the new session is in action, but none of the session["values"] have persisted across the two requests. As you can see from the code below i've tried adding the values to a number of collections to avail.
Any help would be amazing!! Thanks in advance
bool IsAdded = false;
bool IsRedirect = false;
HttpSessionState state = HttpContext.Current.Session;
SessionIDManager manager = new SessionIDManager();
HttpStaticObjectsCollection staticObjects = SessionStateUtility.GetSessionStaticObjects(HttpContext.Current);
SessionStateItemCollection items = new SessionStateItemCollection();
foreach (string item in HttpContext.Current.Session.Contents)
{
var a = HttpContext.Current.Session.Contents[item];
items[item] = a;
}
HttpSessionStateContainer newSession = new HttpSessionStateContainer(
manager.CreateSessionID(HttpContext.Current),
items,
staticObjects,
state.Timeout,
true,
state.CookieMode,
state.Mode,
state.IsReadOnly);
foreach (string item in HttpContext.Current.Session.Contents)
{
var a = HttpContext.Current.Session.Contents[item];
newSession.Add(item,a);
}
SessionStateUtility.RemoveHttpSessionStateFromContext(HttpContext.Current);
SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, newSession);
manager.RemoveSessionID(HttpContext.Current);
manager.SaveSessionID(HttpContext.Current, newSession.SessionID, out IsRedirect, out IsAdded);
return newSession.SessionID;
Maybe I'm missing something here but won't this work:
Session["mysession"] = mySessionObject;
Basically it appears it's not possible since you can only add session variables once there has been one round trip to the client to create the corresponding session cookie. Therefore I had to create the new new session (with new ID) so that by the time I came to adding session variables, the client cookie had the appropriate session id: annoying since this in reality is issuing the new session ID before the user is authenticated.
Interestingly, it seems a little strange that issuing a new Session ID is exactly what the standard asp.net authentication/ membership functionality does but is able to maintain session variables, and yet doing it manually it doesn't....are there some methods for this that are not being exposed to us mere developers maybe....

Resources