I am facing a problem,
I have set session time out in web.config
<system.web>
<sessionState timeout="60" mode="InProc" />
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
</system.web>
In my controller
public ActionResult CreateBrand()
{
Session.Timeout=60;
Purchase purchase = Session["purchaseItem"] as Purchase;
if (purchase!=null && purchase.Brand != null)
{
return View(purchase.Brand);
}
return View();
}
You never actually ask a question, so I'll take a stab at guessing what you're asking...
<sessionState timeout="60" mode="InProc" />
When mode="InProc", setting timeout="60" usually does not extend the session timeout beyond 20 minutes because the application pool will spin down (by default) after 20 minutes.
No application pool = no process = no session.
Either change your application pool settings or use a different session state provider.
Related
In my web application, there is an administrator ability to change the validation method/algorithm to SHA1 to HMACSHA256, HMACSHA384, etc. etc.
In the code, when I retrieve the value from the web.config using ConfigurationManager, it shows as being updated.
However, when I open up the Web.config itself, the value does not appear in the MachineKey section. Why is it now showing up?
edit: The technloogy I am using is Visual Studio C# and MVC. A portion of the web.config is below:
<system.web>
<machineKey validationKey="22FEA7D6533FCCE331C2342A1801051F5E2890749CB2D5EF2EEABF8B0D944F389F46FA061D1A203EB75F3A9197914299676917FFD355456CFA0B49CA4C30B348"
decryptionKey="30B2FA2A8C54665E18D9A35E3541BFED6A3E8A640DBA4070" />
<authentication mode="Forms">
<forms name="FormsAuth1" loginUrl="https://localhost/OidcApplication/Oidc/Authenticate" timeout="2880" requireSSL="false" />
</authentication>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
This is how I retrieve the machine key values:
machineKeyConfig = (MachineKeySection)GetConfigurationSection("system.web/machineKey");
And this is how I set the machine key values:
var machineKeyConfig = (MachineKeySection)GetConfigurationSection("system.web/machineKey");
machineKeyConfig.DecryptionKey = machineKeySettings.DecryptionKey;
machineKeyConfig.Validation = machineKeySettings.Validation;
machineKeyConfig.ValidationKey = machineKeySettings.ValidationKey;
machineKeyConfig.CurrentConfiguration.Save(ConfigurationSaveMode.Minimal);
First of all, I would check whether the file you are saving to is the same you are reading:
var ConfigFilePath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
By the way, what's the class and namespace of the GetConfigurationSection method?
I'm have a mvc app that use with form authentication security client and all the manage user's is made in server side with wcf protocol.
and in the server site I'm saving the user tocken in the sessoin
string token = Srv.ValidateUser(out isNewUser, model.UserName, model.Password, model.IdentityNumber);
if (!string.IsNullOrEmpty(token))
{
Session["Token"] = token;
}
with this token I Identifies in the services
and the user name in the form authentication
FormsAuthentication.SetAuthCookie(model.UserName, false);
and now I dont know how to force user change password after first login or after password expired.
My config is:
<system.web>
<sessionState mode="InProc" cookieless="true" timeout="20" />
<authentication mode="Forms">
<forms path="/" loginUrl="~/Account/Login" />
</authentication>
<authorization>
<allow users="*" />
<deny users="?" />
</authorization>
<identity impersonate="true" />
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Can anyone help me?
In your Login post action, you can check LastPasswordChangedDate like so:
var currentUser = Membership.GetUser(model.Email);
if (currentUser != null)
{
if (currentUser.LastPasswordChangedDate == currentUser.CreationDate)
{
// User has not changed password since created.
return RedirectPermanent("Login/?userName=" + model.Email);
}
}
I have been faced with this problem for months and I have read almost all I can about this and implemented most solutions but still nothing has changed. I don't know where I am making my mistake.
I am using a custom SessionManager class to get/set values into Session easily in my ASP.net CMS websites' admin panels. When the user logins I store user data to the Session then read in Admin.master page to check if the user is logged in. On different servers and also on localhost, the SessionManager.CurrentUser value is null at random times, sometimes 2 minutes sometimes 20 minutes after login, whether the page is idle or not. All my websites have the same problem.
My SessionManager.cs is
public class SessionManager
{
public SessionManager() { }
public static User CurrentUser
{
get { return (User)HttpContext.Current.Session["crntUsr"]; }
set { HttpContext.Current.Session["crntUsr"] = value; }
}
public static string CurrentAdminLanguage
{
get
{
if (HttpContext.Current.Session["crntLang"] == null) HttpContext.Current.Session["crntLang"] = SiteSettings.DefaultLanguage;
return HttpContext.Current.Session["crntLang"].ToString();
}
set
{
HttpContext.Current.Session["crntLang"] = value;
}
}
}
Note: User class is [Serializable]
In Admin.master Page_Load
if (SessionManager.CurrentUser == null) Response.Redirect("../login");
In web.config
<system.web>
<sessionState mode="InProc" customProvider="DefaultSessionProvider" cookieless="UseCookies" regenerateExpiredSessionId="true" timeout="60"/>
<machineKey validationKey="CC0...F80" decryptionKey="8BF...1B5" validation="SHA1" decryption="AES"/>
<authentication mode="Forms">
<forms loginUrl="~/login" timeout="60" slidingExpiration="true" cookieless="UseCookies" />
</authentication>
<system.webServer>
<modules>
<remove name="Session"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</modules>
I really have no more ideas to solve this issue. Please help :(
Have you checked your application pool recycling timeout? That's a common issue for session "disappearing" prior than expected. Check in IIS
If you have problems, you could set up SQL Server for handling the session, which will persist it if the AppPool is recycled, or the server is rebooted.
For more information: http://support.microsoft.com/kb/317604
Here is a sample web.config code. I don't like the regenerateExpiredSessionId in there and also it is a good practice to have your session timeout to be less than your forms timeout. How ever my advice is to carefully examine your session manager code so you can be sure that you don't reset it somehow. I can think of two thing you could do:
1. Make a test page to check when the session is empty or not and to see if you can at all set a session variable. Try to do a button click (or a ajax request) and set a session variable to keep the session alive every 1 minute or so to see if it expires again even if you keep it alive. If you don't use the Session it will expire. 2. Do some kind of logging. Every time you set a session variable do a DB log of the variable you have set. You could use the test page in 1 to see what exactly you have set in session for the current user.
<authentication mode="Forms">
<forms name="Web-site.ASPXAUTH" loginUrl="~/admin/login.aspx" protection="All" timeout="60" path="/" requireSSL="false" slidingExpiration="true" cookieless="UseDeviceProfile" domain="" enableCrossAppRedirects="false" />
</authentication>
<sessionState timeout="60" mode="InProc" />
<membership defaultProvider="WebSiteMembershipProvider">
<providers>
<clear />
<add name="WebSiteMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="DefaultConnStr" applicationName="web-site" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" requiresQuestionAndAnswer="false" enablePasswordReset="true" enablePasswordRetrieval="false" passwordFormat="Hashed" requiresUniqueEmail="false" />
</providers>
</membership>
<roleManager defaultProvider="WebSiteRoleProvider" enabled="true" cacheRolesInCookie="true" cookieName="Web-Site.ASPXROLES" cookieTimeout="60" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="All" createPersistentCookie="false" maxCachedResults="25">
<providers>
<clear />
<add name="WebSiteRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="DefaultConnStr" applicationName="web-site" />
</providers>
</roleManager>
I have an asp.net app with master pages. I need to have a session timeout after 10 minutes, for which I have a javascript code block. Is there any other more efficient way to do a session timeout rather than have a javascript code block on every page? (I am not using membership provider).
You can change the timeout of your session in your web.config
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="10"
sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
sqlCommandTimeout="30"
customProvider=""
cookieless="UseCookies"
cookieName="ASP.NET_SessionId"
timeout="10"
allowCustomSqlDatabase="false"
regenerateExpiredSessionId="true"
partitionResolverType=""
useHostingIdentity="true">
<providers>
<clear />
</providers>
</sessionState>
reference:http://msdn.microsoft.com/en-us/library/h6bb9cz9(vs.80).aspx
you can simply do this on server side. there is no point to time your session on client side. in that case, you can do it centrally on master page or webconfig or global.asax.
Using javascript is a bad idea, you can do what you want easily on the server.
Add this to your Global.asax
protected void Session_Start(object sender, EventArgs e)
{
Session.Timeout = 10;
}
And this to your web.config
<configuration>
<system.web>
<sessionState timeout="10"></sessionState>
</system.web>
</configuration>
You need to add both to make it work effectively.
You can made changes in web.config file by adding following to have session timeout:
<system.web>
<authentication mode="Forms">
<forms timeout="10"/>
</authentication>
<sessionState timeout="10" />
</system.web>
You can do it from c# by using following code:
Session.Timeout = 10;
I am having difficulties implementing a custom ASP.NET RoleProvider.
First off, let me show you the relevant settings in my web.config file:
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="Default.aspx"
timeout="20"/>
</authentication>
<membership defaultProvider="MembershipProvider">
<providers>
<clear />
<add name="MembershipProvider"
type="CompanyName.Security.MembershipProvider" />
</providers>
</membership>
<roleManager defaultProvider="RoleProvider"
enabled="true">
<providers>
<clear />
<add name="RoleProvider"
type="CompanyName.Security.RoleProvider" />
</providers>
</roleManager>
</system.web>
<location path="Employees.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow roles="Employees"/>
</authorization>
</system.web>
</location>
</configuration>
Here's the code for the login button's event handler:
if (Membership.ValidateUser(tbxUsername.Text, tbxPassword.Text))
Response.Redirect("./Employees.aspx");
else
{
tbxUsername.Text = string.Empty;
tbxPassword.Text = string.Empty;
tbxUsername.Focus();
lblLogin.Visible = true;
}
Side Note based on FormsAuthentication.RedirectFromLoginPage() suggestion:
[It has been suggested that I use FormsAuthentication.RedirectFromLoginPage() instead of Response.Redirect(). Eventually, I'd like to redirect the user to a different page based on his/her role. I don't know how FormsAuthentication.RedirectFromLoginPage() would allow me to do this as it does not accept a redirection url as a parameter. In addition, it is my understanding that I could call FormsAuthentication.SetAuthCookie() prior to Response.Redirect() in order to create the authentication cookie that FormsAuthentication.RedirectFromLoginPage() creates. Please let me know if my thought process here is wrong.]
After stepping through the source, I can see that Membership.ValidateUser() is executing the ValidateUser() function of my custom MembershipProvider class. However, when a valid user logs in, and is redirected to Employees.aspx, the user is returned to Login.aspx**?ReturnUrl=%2fEmployees.aspx**. I assume that this is because although the user authenticates, s/he is failing authorization to the Employees.aspx resource.
With that assumption, I created breakpoints on every function in my custom RoleProvider class to see where things run amuck. Not one of them breaks execution when I debug. Most of the code in my RoleProvider throws NotYetImplementetExceptions, but I would still expect to hit the breakpoints (and would then implement those required functions). Here are two dumbed-down functions I have implemented:
public override string[] GetRolesForUser(string username)
{
return new string[1] {"Employees"};
}
public override bool IsUserInRole(string username, string roleName)
{
return true;
}
I assume that since the RoleProvider code never executes, that something must be wrong with my web.config.
I've searched for an answer to this for the past two days and have tried various changes without success. Does anyone see where I'm going wrong?
Thanks in advance!
After authenticating the user using Membership.ValidateUser, you should call FormsAuthentication.RedirectFromLoginPage rather than Response.Redirect to create the forms authentication ticket.
See the MSDN documentation for Membership.ValidateUser for an example.
EDIT
Or if you want to redirect to a specific page, call FormsAuthentication.SetAuthCookie to create the forms authentication ticket before calling Response.Redirect.
It redirects authenticated users to default.aspx
Actually it redirects back to the page that was originally requested, which is not necessarily default.aspx
EDIT 2
Also there is a problem with your configuration:
The path attribute should not point to a specific page (Default.aspx in your case), but the root directory of the site. The default is "/" because most browsers are case-sensitive and so won't send the cookie if there is a case mismatch.
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="/"
timeout="20"/>
Check if user is in role:
If (Roles.IsUserInRole("Employees"))
{
}
or try if it works without role checking:
<allow users="*"/>
maybe helps configuration change:
<location path="Employees.aspx">
<system.web>
<authorization>
<allow roles="Employees"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
I changed the path value (see below) from "Default.aspx" to "/" and now the breakpoints in the custom RoleProvider are being hit!
Does not work:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="Default.aspx"
timeout="20"/>
</authentication>
Works:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
name="FormsAuthentication"
path="/"
timeout="20"/>
</authentication>