I'm creating a website to work with a game app where alliances can battle against one another.
This is my first attempt at a webpage and I'm trying to pass an ID to another page. The problem is that my page_load fires the first time and I set the ViewState variables but then my master page loads which causes everything to be reset.
First page:
FindOpponent.aspx (button click sets the ID and then proceeds to here)
Context.Items["WarID"] = tw.ID;
Server.Transfer("ConfirmWarTimer.aspx");
Second Page:
ConfirmWarTimer.aspx (Everything works the first time Page_Load gets called. ViewState contains my variable and timer is enabled)
protected void Page_load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ActivateTimer();
return;
}
}
public void ActivateTimer()
{
if (!tim.Enabled)
{
DBClassesDataContext db = new DBClassesDataContext();
if (Context.Items["WarID"] != null)
{
ViewState["WarID"] = Context.Items["WarID"];
var thisWar = from a in db.tblWars where a.ID == int.Parse(ViewState["WarID"].ToString()) select a;
foreach (var a in thisWar)
{
TimeSpan t = TimeSpan.Parse(a.CountDown.ToString());
ViewState["Hours"] = t.Hours;
ViewState["Minutes"] = t.Minutes;
ViewState["Seconds"] = t.Seconds;
ViewState["TimeStamp"] = a.TimeStamp.ToString();
}
}
lblStart.Value = ViewState["TimeStamp"].ToString();
tim.Enabled = true;
return;
}
}
But then the master page init/preload/load get called. After that, the Page_Load gets called again on my second page but this time the Context.Items is blank and the ViewState is blank and the timer.enabled is false.
Master Page cs (This is just the page that was created with my project. I added the page_load so the menu wouldn't show on the default.aspx page.)
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// 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;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
}
else
{
// Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if ((Request.Url.ToString().ToLower().IndexOf("default") > -1))
{
pnMenu.Visible = false;
}
else
{
pnMenu.Visible = true;
}
}
protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
{
Context.GetOwinContext().Authentication.SignOut();
}
I've tried to understand viewstate and when to set it and where but after many attempts and changes, viewstate never seems to stick around in my page.
How can I get the viewstate to persist on the second page (ConfirmWarTimer.aspx) after my masterpage 'loads' have executed?
Related
I have some dropdowns to choose between a few dates. The issue is that after choosing the date, the user needs to log in. After that, all the session of member date refreshing the choosing date lost (is not only the js, a lot of date coming because of the relevant choosing.
I tried to save the selected item in a cookie, but it didn't work.
I have the session of the index
private int getIndexFromSession()
{
int index = 0;
if (Session["DTF_selectedIndex"] != null)
{
index = (int)Session["DTF_selectedIndex"];
// Session.Remove("DTF_selectedIndex");
if (index > dateTimeFilter.Items.Count)
index = 0;
}
return index;
}
the drop down in .aspx:
<asp:DropDownList ID="dateTimeFilter" runat="server" OnSelectedIndexChanged="dateTimeFilter_SelectedIndexChanged"
and .cs
protected void dateTimeFilter_SelectedIndexChanged(object sender, EventArgs e)
{
// showsDatalistPanel.Visible = true;
DropDownList ddl = (DropDownList)sender;
if (ddl.SelectedValue != "0")
{
Session["DTF_selectedIndex"] = ddl.SelectedValue;
HttpCookie cookie = new HttpCookie("DTF_selectedIndex", ddl.SelectedValue);
DateTime now = DateTime.Now;
cookie.Expires = now.AddMinutes(10);
Response.Cookies.Add(cookie);
}
}
and the request
protected void Page_Load(object sender, EventArgs e)
{
if (Session["DTF_selectedIndex"] != null)
{
Session["DTF_selectedIndex"] = Request.Cookies["DTF_selectedIndex"];
}
}
I want before or after each login to each user Give a new Session ID. I use Asp.net and IIS 8.0 and windows 2012 server.
I used this method
protected void Page_Load(object sender, EventArgs e)
{
Session["userid"] = txt_user_name.Text;
if (Session["userid"] != null && Session["AuthToken"] != null && Request.Cookies["AuthToken"] != null)
{
if (!Session["AuthToken"].ToString().Equals(Request.Cookies["AuthToken"].Value))
{
lbl_message.Text = "NOT LOGIN";
}
}
if (txtInput.Text == "")
{
CreateSesstion_Click(sender, e); // This method Generate new Session Id
}
if (!IsPostBack)
{
Captcha();
}
}
protected void CreateSesstion_Click(object sender, EventArgs e)
{
SessionIDManager manager = new SessionIDManager();
string newID = manager.CreateSessionID(Context);
bool redirected = false;
bool isAdded = false;
manager.SaveSessionID(Context, newID, out redirected, out isAdded);
HttpContext.Current.Session["x"] = 123;
}
This method works fine before publishing it, but after publishing when the site runs with HTTPS, it fails and does not recognize the new Session ID. And makes a mistake.
If it's open without SSL, it works fine
Please help me
Thankful
I'm doing a session ID change, but when it redirects to the Default.aspx page it loses all the keys I assigned to it!
this strange, any clue or help?
Even when I'm commenting this part :
Session.Clear();
Session.Abandon();
Session.RemoveAll();
if (Request.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
}
it loses everything!
Here is my code:
protected void btnDebugLogin_Click(object sender, EventArgs e)
{
try
{
string email = "test#123.com";
string pw = "password";
string ip = Request.UserHostAddress.ToString();
string browseragent = Request.UserAgent.ToString();
ConsoleUser loginUser = new ConsoleUser();
AbandonSession();//Delete any existing sessions
var newSessionId = CreateSessionId(HttpContext.Current); //Create a new SessionId
SetSessionId(HttpContext.Current, newSessionId);
loginUser = SecureLogin.Login(email, pw, ip, browseragent, referrer, LangCode, Session.SessionID.ToString(), null);
if (loginUser == null)
{
lblMsg.Visible = true;
}
else
{
Session["CurrentUser"] = loginUser;
Session["CurrentLoginID"] = loginUser.CurrentLoginId; // Used for tracking User Activity in KeepSessionAlive
Response.Redirect("/qConsole/Default.aspx",false);
}
}
catch(Exception ex)
{
}
}
protected void AbandonSession()
{
Session.Clear();
Session.Abandon();
Session.RemoveAll();
if (Request.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
}
if (Request.Cookies["__AntiXsrfToken"] != null)
{
Response.Cookies["__AntiXsrfToken"].Value = string.Empty;
Response.Cookies["__AntiXsrfToken"].Expires = DateTime.Now.AddMonths(-20);
}
}
private static string CreateSessionId(HttpContext httpContext)
{
var manager = new SessionIDManager();
string newSessionId = manager.CreateSessionID(httpContext);
return newSessionId;
}
public static void SetSessionId(HttpContext httpContext, string newSessionId)
{
var manager = new SessionIDManager();
bool redirected;
bool cookieAdded;
manager.SaveSessionID(httpContext, newSessionId, out redirected, out cookieAdded);
}
and the validation part is done in the Master Page before the Default.apsx page is loaded, here:
protected void Page_Init(object sender, EventArgs e)
{
if (Session["CurrentUser"] == null)
{
Response.Redirect("/");
}
// ..
}
This is the expected result of telling the client to use a new session id. The values are still in the old session, but there is no connection between the old one and the new one. The Session is attached to the request early on in the request cycle, and changing a cookie value during the handling won't affect what session is attached to the user's requests until the next request comes in. What you want to do is clear the cookie when you first render the page, not when they click the button. There are some other subtleties to session management that I mention in my answer https://stackoverflow.com/a/45383679/10558.
You've tagged this question csrf but your solution does nothing for that attack. What resetting the session id prevents is session fixation.
I am creating a custom login page for a sharepoint forms based authentication.
The default page has a login control, and the login control has 2 methods, the signing in and the onauthorize.
The signin gets a userid, whera later I need it to verify the SMS with an external sms provider.
I tried to do this with Session but I get this error
Session state can only be used when enableSessionState is set to true,
either in a configuration file or in the Page directive. Please also
make sure that System.Web.SessionStateModule or a custom session state
module is included in the \\
section in the application configuration.
Code
namespace Authentication.FBA2FA.CustomLogin.Layouts.Authentication.FBA2FA.CustomLogin
{
public partial class CustomLoginPage : FormsSignInPage
{
private string cellnumber;
private bool siCell;
AuthyClient client;
private string useridAuthy;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void signInControl_Authenticate(object sender, AuthenticateEventArgs e)
{
SecurityToken token = null;
LoginControl formsLoginControl = sender as LoginControl;
TextBox txtphone = (TextBox)signInControl.FindControl("tbxPhone");
TextBox txtSecureCode = (TextBox)signInControl.FindControl("tbxSecureCode");
client = GetAuthyClient();
// I need to get the user id here.
var tokenresult = client.VerifyToken(Session["userid"].ToString(), txtSecureCode.Text);
if (tokenresult.Status != AuthyStatus.Success)
{
siCell = true;
}
else
{
siCell = false;
}
//bSendSms.Click += bSendSms_Click;
if (null != (token = GetSecurityToken(formsLoginControl)))
{
if (siCell)
{
EstablishSessionWithToken(token);
e.Authenticated = true;
base.RedirectToSuccessUrl();
}
else
{
e.Authenticated = false;
}
}
}
//private void bSendSms_Click(object sender, EventArgs e)
//{
//}
private SPIisSettings IisSettings
{
get
{
SPWebApplication webApp = SPWebApplication.Lookup(new Uri(SPContext.Current.Web.Url));
SPIisSettings settings = webApp.IisSettings[SPUrlZone.Default];
return settings;
}
}
private SecurityToken GetSecurityToken(LoginControl formsLoginControl)
{
SecurityToken token = null;
SPIisSettings iisSettings = IisSettings;
Uri appliesTo = base.AppliesTo;
if (string.IsNullOrEmpty(formsLoginControl.UserName) || string.IsNullOrEmpty(formsLoginControl.Password))
return null;
SPFormsAuthenticationProvider authProvider = iisSettings.FormsClaimsAuthenticationProvider;
token = SPSecurityContext.SecurityTokenForFormsAuthentication(
appliesTo,
authProvider.MembershipProvider,
authProvider.RoleProvider,
formsLoginControl.UserName,
formsLoginControl.Password);
return token;
}
protected void btnSms_Click(object sender, EventArgs e)
{
TextBox txtSecureCode = (TextBox)signInControl.FindControl("tbxSecureCode");
TextBox txtphone = (TextBox)signInControl.FindControl("tbxPhone");
int n;
bool isNumeric = int.TryParse(txtphone.Text, out n);
if (string.IsNullOrEmpty(txtphone.Text) && !isNumeric)
{
ClaimsFormsPageMessage.Text = "Please insert a cellphone number";
}
else
{
cellnumber = txtphone.Text;
client = GetAuthyClient();
var result = client.RegisterUser("univer.diego.s#gmail.com", cellnumber, 57);
useridAuthy = result.UserId;
// I need to set the user id here.
Session["userid"] = useridAuthy;
client.SendSms(result.UserId, true);
}
}
}
}
Because this is Sharepoint, I am not sure if I should do something in the web.config for the web application and if it will do any damage to sharepoint itself.
thanks a lot
Instead of modifying SharePoint's web.config file(s), you can just add EnableSessionState="True" to the Page directive on your custom page.
<%# Page Language="C#" EnableSessionState="True" ... %>
I have the following code in my Global.asax
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Handler is IRequiresSessionState)
{
if (Request.IsAuthenticated)
{
if (HttpContext.Current.Session[this.MemberShipProvider.PrincipalSessionKey] != null)
{
CxPrincipal principal;
try
{
principal = (CxPrincipal)HttpContext.Current.Session[this.MemberShipProvider.PrincipalSessionKey];
}
catch
{
principal = null;
}
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
}
else
{
var identity = new CxIdentity("admin", 1, "", true);
CxPrincipal principalLogin = new CxPrincipal(identity, 1);
HttpContext.Current.Session[this.MemberShipProvider.PrincipalSessionKey] = principalLogin;
HttpContext.Current.Session[SessionName.CurrentUser] = "Admin User";
HttpContext.Current.User = principalLogin;
Thread.CurrentPrincipal = principalLogin;
this.FormServiceProvider.SignIn("admin", false); // this is equal to FormsAuthentication.SetAuthCookie
}
}
}
}
The problem is that everytime the Session is object is null. Not only here, I can't use sessions in my application as well. Either the session is being Reset or something like that.
My application doesn't require the user to Login anymore. Therefore I am not using Session.Clear or Session.Abandon any where in my application.
Please help me, why is my session variable not setting?
You need to implement (and m.b. leave empty) 2 methods in your global.asax.cs:
void Session_Start(object sender, EventArgs e)
{
}
void Session_End(object sender, EventArgs e)
{
}