How to clear ALL active sessions in asp.net - asp.net

1) I'd like to know how can I clear all sessions in asp.net so every user logged to a system can't work unless they log-in again.
2) Is there any way to iterate through all sessions to make an exception for admin users stored in session?
Thanks in advance!
Regards.

You cannot access Session state from within another session however you can share data via the Application state and use that to kill other sessions when they next do a request via Global.asax
Keep track of time when each session was started via Session_Start in Global.asax
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["dtmStart"] = DateTime.Now;
}
Abandon each session when it next requests via Application_AcquireRequestState in Global.asax if the session was started before the current kill time stored in Application state
void Application_AcquireRequestState(object sender, EventArgs e)
{
// Occurs as the first event in the HTTP pipeline chain of execution when ASP.NET responds to a request.
// Check if session should be killed
if (Application["dtmClearSessions"] != null
&& Session["dtmStart"] != null
&& (DateTime)Application["dtmClearSessions"] > (DateTime)Session["dtmStart"])
{
// Check if user is an administator
if (Application["lstAdminUserIds"] != null && Session["intMyUserId"] != null)
{
List<int> lstAdminUserIds = (List<int>)Application["lstAdminUserIds"];
int intMyUserId = (int)Session["intMyUserId"];
if (lstAdminUserIds.Contains(intMyUserId))
return;
}
Session.Abandon();
}
}
To flag that the sessions should be abandoned simply set Application["dtmClearSessions"] = DateTime.Now; for example via a button press on a page.
protected void btnKillEmAll_Click(object sender, EventArgs e)
{
try
{
Application["dtmClearSessions"] = DateTime.Now;
}
catch (ThreadAbortException ex) { throw ex; }
catch (Exception ex)
{
// TODO: RecordError(ex, "my_page.btnKillEmAll_Click", Request);
// TODO: show error on screen litError.Text = ex.Message;
}
}

Related

Access Session object at Session_End Event in Globle.asax file

I want to access session variable at Session_End event of globle.asax file.But HtppContext.Current returns null. Please suggest any other way.
protected void Session_End(object sender, EventArgs e)
{
if (HttpContext.Current != null)
{
HttpContext ht = HttpContext.Current;
string username = ht.Session["UserName"].ToString();
}
}
I was facing the same problem yesterday, and I simply use:
string username = Session["UserName"].ToString();

ASP Membership Current user not taking the right value

i am using an ASP control Login and i want to redirect the user logged in depending on its role. But it seems like The User take the previous value of the last logged in user. seems problem of refresh the current user or something like this
Code of my webform1.aspx.cs:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
TextBox1.Text = Context.User.Identity.Name.ToString();
if (Context.User.IsInRole("admin"))
{
Response.Redirect("~/admin.aspx");
}
else if (User.IsInRole("user"))
{
Response.Redirect("~/user.aspx");
}
}
Inside LoggedIn event of Login control, principal object hasn't been attached to the current HttpContext yet.
Therefore, you cannot use Context.User inside LoggedIn event.
protected void Login1_LoggedIn(object sender, EventArgs e)
{
var roles = Roles.GetRolesForUser(Login1.Username);
if (roles.Contains("admin"))
{
Response.Redirect("~/admin.aspx");
}
else if (User.IsInRole("user"))
{
Response.Redirect("~/user.aspx");
}
}

how to show the message for session expired in asp.net using httpcontext

Redirecting user to login page after session timeout is similar to refreshing the page after certain intervals method. Only thing which will differ is that calculating time after which the page has to be redirected. Hence time can be calculated using Session.timeout property which will give us session timeout value for that session. Add some grace timings to that value and redirect the user to the login page automatically.
protected void Page_Init(object sender, EventArgs e)
{
CheckSession();
}
private void CheckSession()
{
if (Session["SessionID"] == null)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect", "var r = confirm('Your Session Has Expired'); if (r == true) var str= 'PartnerLogin.aspx'; location.href = str ;", true);
}
}

Accessing Sessions Variables in code behind

Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Session["Authenticated"] )
{
Response.Redirect( "index.aspx", false );
}
}
Once they login I set the session to true. Basically, if they don't have an active session I want them re-directed back to the index/login page. How do I accomplish this?
Use this check
if(Session["Authenticated"] == null || !(bool)Session["Authenticated"])
If you are using cookie, you can store a marker in your cookie so you can tell the difference between "fresh browser + new session" and "old browser + expired session".
Below is sample code that will redirect the user to an expired page if the session has expired.
void Session_OnStart(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
HttpCookieCollection cookies = context.Request.Cookies;
if (cookies["starttime"] == null) {
HttpCookie cookie = new HttpCookie("starttime", DateTime.Now.ToString());
cookie.Path = "/";
context.Response.Cookies.Add(cookie);
}
else {
context.Response.Redirect("expired.aspx");
}
}
And if you are trying to implement sessions this might help you http://aspalliance.com/1621_Implementing_a_Session_Timeout_Page_in_ASPNET.2

How to properly authenticate mvc-mini-profiler with AspNetSqlMembershipProvider

I tried to check if the user is in role at Application_BeginRequest and Application_AuthenticateRequest with this code and it will not work. At BeginRequest the code is never hit and Authenticate it's hit with some of the request and the profiler does not show up.
Checking only for Request.IsLocal works fine.
if(Request.IsAuthenticated)
{
if(User.IsInRole("Admin");
MiniProfiler.Start();
}
Any idea or why it's not working or better way to do it?
[Update] I accepted the awnser but undid it as I didn't quite get it do work
I did the following but the profiler is not showing up at first.
After a few tries it started showing up, even when I tried to acess the site with incognito mode, so no cookie.
protected void Application_PostAuthorizeRequest(Object sender, EventArgs e)
{
if (User.IsInRole("Admin"))
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if (cookie == null)
{
cookie = new HttpCookie("RoleProfiler");
cookie.Value = "yes";
cookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookie);
}
}
}
And I'm checking with
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if ((cookie != null) && (cookie.Value == "yes") )
{
MvcMiniProfiler.MiniProfiler.Start();
}
}
And ending at the end of the request.
protected void Application_EndRequest()
{
MvcMiniProfiler.MiniProfiler.Stop();
}
[Update2] Closing question, ignore this, I was being owned by outputcache.
The cookie feanz mentions is a handy trick, a second method is profiling unconditionally and then abandoning the session for an unauthenticated user:
protected void Application_BeginRequest()
{
MvcMiniProfiler.MiniProfiler.Start();
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if(!CurrentUserIsAllowedToSeeProfiler())
{
MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
}
}
Begin request happens before the user is fully authenticated in the request life cycle.
I solved this issue by adding a cookie if the user is in a role ("Admin" in your case) when the request is authenticated then you can check for this cookie on begin request and initialise the profiler.
It wont't work the first time but should every time after that.
This is my 2cent.
context.AcquireRequestState += (sender, e) =>
{
// Check debug in session. Can be set from Querystring. (?debug=true)
if (HttpContext.Current.Session != null && HttpContext.Current.Session["Debug"] != null)
{
try{
bool debug = (bool)HttpContext.Current.Session["Debug"];
if (debug == true)
MiniProfiler.Start();
else
MiniProfiler.Stop(discardResults: true);
}
catch{
MiniProfiler.Stop(discardResults: true);
}
}// Or always show if Administrator.
else if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
bool admin = HttpContext.Current.User.IsInRole("Administrator");
if (admin == false)
{
MiniProfiler.Stop(discardResults: true);
}
}
else
{
MiniProfiler.Stop(discardResults: true);
}
};

Resources