Losing ASP session variables, or so I think - c#

I have a relatively simple ASP.Net application that I have built some simplistic security into. The user logs in with a username and password and I check it against the DB. If it is successful I store a User object for them on a session variable called "UserID" and redirect them to the same page, only this time they dont see the login panel. (Mmm could just hide it dynamically but I think that would cause a page reload anyway)
On my Default.aspx page I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserID"] == null)
{
LoginPanel.Visible = true;
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
Security security = new Security();
Session["UserID"] = security.LoginUser(txtUsername.Text, txt2Password.Value);
if (Session["UserID"] != null)
{
Response.Redirect("~/default.aspx");
}
}
Right, so far so good. Also worth mentioning at this point is the master page:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserID"] == null)
{
//Check that we are not already on the default.aspx page.
//Don't want to cause infinite redirect here
if (!Request.Path.ToLower().Contains("default.aspx"))
{
Page.Response.Redirect("~/Default.aspx");
}
}
else
{
//Otherwise we get the UserObject from the session and display menu items //based on the role. Nothing fancy.
}
}
//Bad naming. This a logout link on the master...
protected void Unnamed1_Click(object sender, EventArgs e)
{
Session["UserID"] = null;
Page.Response.Redirect("~/Default.aspx");
}
Now all of this works perfectly on my local instance of IIS. As soon as I deploy this to our production server and I click on one of my menu items and navigate say to Search.aspx it chucks me back to my Default.aspx page with the LoginPanel visible??? Also that is in Firefox. With IE I can click on the Search.aspx menu link and it takes me to the page, but clicking on an edit link in my GridView also chucks me back to the Default.aspx page with the LoginPanel showing.
I'm no ASP.net expert at all and I'm at wits end. So please word Answers with as little as possible jargon and so forth and post links to msdn for docs and such so that I don't just resolve this, but actually understand why this has been giving me nightmares.
TIA

Don't store user identifiers or other sensitive information in the session, implement IIdentity and IPrincipal with Forms authentication instead (though this doesn't completely rule out information exposure altogether).
This enables easy access to certain elements in the nature of what you need:
//to sign-in:
FormsAuthentication.SignIn("username", createPersistentLogin);
//to sign-out:
FormsAuthentication.SignOut();
//user data access:
Page.User.IsInRole("requiredRole");
Page.User.Identity.IsAuthenticated;
Page.User.Name;
A couple of snippets from MSDN to explain the meaning of this:
The .NET Framework provides a
role-based security implementation in
the System.Security.Principal
namespace, which you can use for
authorizing and authenticating users
in your application.
An IIdentity encapsulates an
authenticated user. An IPrincipal is a
combination of the identity of the
user and any roles he or she has. You
can use the predefined identity and
principal classes in the
System.Security.Principal namespace or
you can add custom authentication by
creating classes that implement the
interfaces.
Care should be used when granting
permissions to work with IIdentity
objects, because these objects make
sensitive user-related information
available. You should protect the
application's current IPrincipal
object from changes because the
application's authorization capability
is based on its current principal.
You can get information on doing this from MSDN.

maybe a bit off topic but I would recommend to use built in login functionality, that means Login Controls, Membership and Authentication. Then you don't have to mess with Session
http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx
then you can do Membership.GetUser().ProviderUserKey for example to get the key

Verify if in your production server the Web.Config file of your site contains this line, or something like this :
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20" />
It must be inside element.
It is to verify wich sessionState are you using.
See the link :
Asp.NET Session State

Related

Restrict URL to specific database username ASP.NET

I am making a website tool isch with ASP.NET Framework, that lets a user/customer preview their website.
I have a simple database that gathers a SESSION["username"] and creates a with the source to the customer project file.
But if I have multiple users how am I supposed to prevent users from accessing each other's files using the URL? like if the directory for the customer projects is ? "~/Customer/SESSION["username"]/Default.aspx and user1 enters user2 in the directory instead. I will post some content of the page here to make it easier to understand.
Directory of my project
In the Default.aspx page I direct everyone that is not the user "admin". And inside the Default.aspx i have an IFrame that looks like this <iframe id="contentPanel1" runat="server" /> and it gets its src attribute from my Default.aspx.cs that looks like this:
using System;
using System.Web.UI;
namespace MyFeedbackWebsite
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] == null)
{
Response.Redirect("~/login");
}
if ((string)Session["username"] == "admin")
{
Response.Redirect("~/admin");
}
this.contentPanel1.Attributes["src"] = "https://localhost:44350/Customer/" + Session["username"].ToString();
}
}
}
In my Admin.aspx.cs I check if the username = admin and if the user is logged in:
using System;
namespace MyFeedbackWebsite
{
public partial class admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if ((string)Session["username"] == null)
{
Response.Redirect("~/Login");
}
if ((string)Session["username"] != "admin")
{
Response.Redirect("~/Default");
}
}
}
}
And in the /Customer/ Directory I want the customers project to be located. But as I mentioned, if the directory is /Customer/user1/Default.aspxI want the user1 value to match the current session. Thanks beforehand!
Best regards Max
A few observations
Now, I don't know the background of this project you're working on, but it seems you are relatively new to some of the concepts, so I'll just list a few things for you to think about:
If this is a new project I would highly recommend you to stop and instead look at ASP.NET Core or similar. .NET Framework is slowly being replaced by .NET Core, so a new project based on .NET Framework (such as ASP.NET Web Forms) will quickly become outdated (if it isn't already from the start).
If this is just a spare time/personal little project, all good (except for above point) - playing around with it is a good way to learn. If it's a commercial or otherwise serious project, however, I would recommend you to read up on security best practices in web applications. Restricting access to a page using a construct like Session["username"] != "admin" is bad business and very error prone. Take a look here for an example of configuring which users or roles can access which pages.
The problem in question
It's still a little unclear to me what part of your code handles/is run when accessing /Customer/user1/Default.aspx. But I would recommend you, that instead of having the username be part of the URL, you are getting the username from the session in the backend instead, and then serving the proper page matching that username:
User accesses the URL /Customer/Default.aspx
Backend verifies that user is logged in. If not, user is redirected to login page
Backend gets the username from the session and returns the page <username>/Default.aspx (note: this is not a URL, but a file path or something similar that points to the page you are serving - the user never sees this)
Now, the user will not be able to see another user's page because /Customer/user1/Default.aspx is not a valid URL - /Customer/Default.aspx is.

Sharepoint 2013 - when user login give a new session token and expire all previous tokens

I have a Sharepoint 2013 application and need to prevent users from login from differents places at same time.
Searching for a good solution I found out that giving a new session token each time the user login is a good solution. Also I will have to expires all older tokens from that user.
How can I do this using c#.Net ?
Try to do it like in normal ASP.NET app, the only difference would be to use session start from HttpModule, not from global.asax.
In your case do following:
Create custom IHttpModule
public class CustomSessionHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
IHttpModule httpModule = context.Modules.Get("Session");
var sessionModule = httpModule as SessionStateModule;
if (sessionModule != null)
{
sessionModule.Start += OnSessionStart;
}
}
public void Dispose()
{
}
private void OnSessionStart(object sender, EventArgs e)
{
//Check if user has active session( in your storage) if yes then invalidate it or block new request
}
}
Add module to the web.config in the farm with SPWebConfigModification to
configuration/system.webServer/modules view feature (as a PoC do it manually)
Ensure that session is enabled in the web.config (as far I remember this is required)
I've tried a lot of solutions to this. I've tried to deal with Sessions, Cookies without success.
My solution was to use some way of verification like IP for instance.
After check the IP (if the user IP changed) the program redirects the user to the following page:
[sharepointsite]/_layouts/closeconnection.aspx?loginasanotheruser=true
This page is from olders versions of Sharepoint and is hidden in the 2013 version.
It forces the user to log in again.
Here is some code example:
if(currentIP != lastIP)
{
updateIP(currentIP);
Response.Write("<sharepointsite>/_layouts/closeconnection.aspx?loginasanotheruser=true");
}
I know this is not the best solution, but was the only one that worked for me.

Response redirect stays on same link (WebForms)

Im using Webforms throught C#
When the users does a certain action it might be redirected to another link, which is not working atm (it was before and i cant rollback the project since idh tfs or github)
The user is on this site:
localhost:53145/VistaUsuario.aspx
When it users fills the form and click accept the code behind is:
Session["user"] = txtDominio.Text;
Response.Clear();
Response.Redirect("FormOrden.aspx");
When it does the action it's redirected to the same link adding this parameters :
localhost:53145/VistaUsuario.aspx?ReturnUrl=%2fFormOrden.aspx
This is the code behind "FormOrden.aspx"
protected void Page_Load(object sender, EventArgs e)
{
string usuario = (string)Session["user"];
if (usuario != null)
{
this.MostrarDatos();
}
else
{
this.DoSomethingElse();
}
}
How to fix this?
It looks like you have Authentication enabled in your web.config. Your session is not authenticated so any attempt to go to another page goes back to the authentication page, which happens to be your current page (likely default.aspx).
The reason you see ReturnUrl="%2fFormOrden.aspx is because that's how Forms Authentication handles redirects after logging in.
Basically, you try to hit a page that requires authentication and are not authenticated. Forms Authentication redirects the request to the login page. Upon Logging in you make a call to FormsAuthentication to RedirectFromLogin page and it goes to the page specified in the ReturnUrl to go back to where the user was trying to go.
Either finish your authentication workflow, or turn off forms authentication in your web.config.

How to use session to make a login page

I'm trying to write a website which based on ASP.Net. When I made a login page with username and Password, and also connected to a SQL-server.
But when I type in the right username and password. It will need to click login twice to login. Once I login, when I go back to the login page. No matter what I'm trying to type in the username and password textbox. The system will always log me in. I heard that the session can help, but I don't have any idea how to use it.
Is there anyone could help me? Or show me some usable code samples please?
Thank you
Jimmy
I second #GojiraDeMonstah's suggestion and would also recommend that you try to use Microsoft's out of the box (OOTB) functionality for handling website security (i.e. authentication, authorization, user management, password reset etc.) as much as possible. There's no reason to go reinventing the wheel when it's all there for you. You can even extend the existing functionality to create your own custom authentication provider but you really want to avoid trying to write one from scratch especially if you're new to this stuff.
Microsoft provides an infinite number of tools and tutorials to allow you to setup all this stuff so easily. Don't try creating your own database unless you really, really have to. Just use the one they provide you and work from that as a starting point.
Here is another great resource that provides a more visual tutorial to show you how easy it is.
Good luck!
The process of supplying a username and password (credentials) and then using the supplied name & password to verify a user is called Authentication. If you google asp.net authentication you will get a zillion results. Here's a good start --> http://support.microsoft.com/kb/301240
Write code like this
FirstPage.aspx(On your first page Login button click)
protected void Login_Click(object sender, EventArgs e)
{
Session["UserName"] = txtUserName.Text;//Store username in session
}
SecondPage.aspx(after login on next page)
protected void Page_Load(object sender, EventArgs e)
{
LabelUserName.Text = Session["UserName"].ToString();//Show username on a label
}
Hope it helps ....
The easiest way I have found is to download the sample pages provided in this example here.
Use the Global.asac file so you don't have to add login code to each and every page in your application.
In the file "Global.asax", define your session in the function "Session_Start()"
protected void Session_Start(Object sender, EventArgs e)
{
//The first Session "Logged" which is an indicator to the
//status of the user
Session["Logged"]="No";
//The second Session "User" stores the name of the current user
Session["User"]="";
//The third Session "URL" stores the URL of the
//requested WebForm before Logging In
Session["URL"]="Default.aspx";
}
In each of the pages you want only authenticated access to check if the user is Logged or not like this:
private void Page_Load(object sender, System.EventArgs e)
{
if(Session["Logged"].Equals("No"))
{
....
}
else
{
....
}
}
In your Login.aspx page check the user name and password from your database with a function like:
if(CheckUser(UserNametxt.Text.Trim()) && CheckPassword(Passwordtxt.Text.Trim())
{
....
}
else
{
....
}
In your codebehind define the functions CheckUser() and CheckPassword() by connecting to your database and passing the variable from the login page.
Download sample files here.

Using sessions for protecting web files to be accessed if the user is logged or not . useful or not?

I have a login page and a global page where the user is redirected to after he logged in.
I need to know if this is a good method for protecting some web files to be accessed if the user is not logged in.
global.aspx code (the protected page where the user is redirected after he logged in)
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Login"] != null)
{
if (Session["Login"].Equals("Logged"))
{
userName.Text = (string)Session["UserTest"].ToString();
}
}
else
Response.Redirect("http://localhost:port/Login.aspx");
}
Login page code:
Session["Login"] = "Logged";
Session["UserTest"] = "Test123";
Response.Redirect("http://localhost:port/Global.aspx");
Thanks
I think you should read about forms authentication. And yet another article about it. The code you have written seems fine but my God, you are reinventing a wheel.
The idea of forms authentication is that the currently authenticated username is stored in an encrypted cookie (unless defined otherwise) and sent along each request. The forms authentication module, once activated, checks for the presence of this cookie on each request and automatically assigns the User property to make it available to all your pages. And if someone attempts to access a protected page, the module simply redirects him to the login page that was configured in web.config. The <location> element in web.config allows you on the other hand to specify which pages/folders of you application require authentication.
So once you activate forms authentication, here's how your protected page could look like:
protected void Page_Load(object sender, EventArgs e)
{
userName.Text = User.Identity.Name;
}
And the Login page (which should not be protected):
public void Login_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(userName.Text, password.Text))
{
FormsAuthentication.RedirectFromLoginPage(username.Text, false)
}
else
{
errorLabel.Text = "Invalid credentials";
}
}
You might also checkout the Login control that could simplify this even further.

Categories

Resources