WebMatrix WebSecurity: Keeps logging out user randomly - session

I'm using WebMatrix and applied a login system on my website. I'm running into a strange problem. My website keeps randomly logging out the user. Happens unexpectedly. Not only on my code, but happens in the WebMatrix sample projects as well.
My Web.Config file is:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="loginUrl" value="~/login" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<sessionState timeout="20" />
<!-- This is for links with incorrect file extensions -->
<!-- This only handles .NET based errors, not classic web like HTML or ASP based extensions -->
<customErrors mode="Off">
<error statusCode="403" redirect="/Shared/Error404.cshtml" />
<error statusCode="404" redirect="/Shared/Error404.cshtml" />
<error statusCode="500" redirect="/Shared/Error500.cshtml" />
</customErrors>
</system.web>
<system.webServer>
<!-- This handles all other types of link errors -->
<httpErrors errorMode="Custom">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/Shared/Error404.cshtml" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add invariant="System.Data.SqlServerCe.4.0" name="Microsoft® SQL Server® Compact 4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
</configuration>
I've defined the session timeout as 20 minutes. I use the same plain way of logging in the user.
if (WebSecurity.Login(email, password, rememberMe)) {
Context.RedirectLocal(returnUrl);
return;
} else {
ModelState.AddFormError("The user name or password provided is incorrect.");
}
And this is how I check whether my user is signed-in or not in secured pages:
if (!WebSecurity.IsAuthenticated) {
Response.Redirect("~/login", true);
}
I've searched a bit on google, there are few people who have also been complaining that WebMatrix WebSecurity randomly logs out user. Sometimes when an activity is performed, like form submission or sometimes a simple url click.
Any ideas or suggestions? Someone even suggested me to dump Razor and move to MVC, it doesn't have this problem. I'm not sure whether thats true.
UPDATE
I have the following code in top of all my secured pages (which require user being logged in). Does anyone think this would be causing the issue?
// Ensure this page is not cached
Response.Expires = -1;
Response.Cache.SetNoServerCaching();
Response.Cache.SetAllowResponseInBrowserHistory(false);
Response.CacheControl = "no-cache";
Response.Cache.SetNoStore();
Thanks
-Faraz Azhar

I will have to check further, i remember some weirdo setting to increase the cookie stay-logged-in time. Here's what's in my config and i don't see anything else that has a time:
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="~/error/"></customErrors>
<compilation debug="true" targetFramework="4.0" />
<authentication>
<forms timeout="10080" />
</authentication>

Related

User-specific IIS config

Under MyProject > Properties > Web there is an option to "Apply server settings to all users" which stores the IIS config in MyProject.csproj.user.
However, there doesn't seem to be a way to set defaults. Meaning anyone who clones the project will have to customize these settings.
Is there a way to set defaults when using user-specific IIS settings?
I've attempted to use environment variables, but Visual Studio complains that it cannot create an IIS binding for http://$(API_HOST):$(API_PORT)/
What is the setting you need to set? This is an important detail.
Most of the configuration could be setted in the web.config file infact this file has a "system.webServer" section dedicated to IIS Configuration.
example:
<system.webServer>
<defaultDocument enabled="true">
<files>
<add value="Default.htm" />
<add value="Index.htm" />
<add value="Index.html" />
</files>
</defaultDocument>
<directoryBrowse enabled="true" />
<httpErrors>
<error statusCode="404" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="my_custom_404.htm" />
</httpErrors>
<security>
<authentication>
<anonymousAuthentication enabled="true" userName="IUSR" />
<basicAuthentication />
<clientCertificateMappingAuthentication />
<digestAuthentication />
<iisClientCertificateMappingAuthentication />
<windowsAuthentication />
</authentication>
<requestFiltering>
<fileExtensions allowUnlisted="true" applyToWebDAV="true" />
<verbs allowUnlisted="true" applyToWebDAV="true" />
<hiddenSegments applyToWebDAV="true">
<add segment="Web.config" />
</hiddenSegments>
</requestFiltering>
</security>
<staticContent lockAttributes="isDocFooterFileName">
<mimeMap fileExtension=".mp3" mimeType="otect/stream" />
</staticContent>
</system.webServer>
source:
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/

IIS Image Cache Directives Cause 500.19 Error

I wanted to add cache header to browser on IIS. I found this:
IIS 7.5 and images not being cached
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" />
</staticContent>
<httpProtocol>
<customHeaders>
<add name="Cache-Control" value="public" />
</customHeaders>
</httpProtocol>
This solves cache problem that Google warned about on PageSpeed test:
https://developers.google.com/speed/pagespeed/insights/
But also this causes 500.19 error, and it says that: "The configuration section 'staticContent' cannot be read because it is missing a section declaration"
My web.config file was look like that:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="false"></compilation>
<authentication mode="Windows"/>
</system.web>
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404" subStatusCode="-1"/>
<error statusCode="404" prefixLanguageFilePath="" path="/rewrite.asp" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
</configuration>
How to prevent this error?

WCF service And Linq

I am using LINQ in a WCF service. I am trying to list all my movies in a grid but my query wont work.
any of you know why?
this is the query:
public List<MovieInfo> GetAllMovies()
{
var queryResult = (from x in db.MovieInfos
select x);
return queryResult.ToList();
}
This is the webconfig:
<configuration>
<connectionStrings>
<add
name="dmaa0913Sem3_1ConnectionString"
connectionString="Data Source=dbname;Initial Catalog=dataname;Persist Security Info=True;User ID=username;Password=password"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
here is the error i get:
Failed to invoke the service. Possible causes: The service is offline
or inaccessible; the client-side configuration does not match the
proxy; the existing proxy is invalid. Refer to the stack trace for
more detail. You can try to recover by starting a new proxy, restoring
to default configuration, or refreshing the service.
The service is online, because i use WCF test client.
I have solved the problem. The query that i use for extracting data from the database i somthing called lazyloading. And WCF have trouble working with this kind of query if the data that need's to be extracted is to complex. It is somthing about how WCF service serialize the service. So what i did to make it work was to go in the Linq datacontex and set the. Serialization Mode to Unidirectional. This worked for me.

MVC 3 App always looking for SQL Express

I am facing an weird issue when I try to deploy my MVC 3 application on the server.
I used the VS2010 publish feature to get my build package for the server.
When I try to browse my application I received the error
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
SQLExpress database file auto-creation error:
The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:
If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: http://go.microsoft.com/fwlink/?LinkId=160102. If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist.
If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database.
Sql Server Express must be installed on the machine.
The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.
I looked at my configuration file and found that default connection strings were present which were
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
So, it made sense that the this connection string was in use. I removed this connection string and all the default configuration for ASP.NET membership and providers.
But, now when I try to browse my application it still showing the same SQLExpress database creation error.
below is my config file.
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<!--Home Connection String-->
<add name="DBEntities"
connectionString="metadata=res://*/EDMX.HostelBookNowDB.csdl|res://*/EDMX.HostelBookNowDB.ssdl|res://*/EDMX.HostelBookNowDB.msl;provider=System.Data.SqlClient;provider connection string="data source=<Server Name>;initial catalog=DB;persist security info=True;Integrated Security=SSPI;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="HotelManagerHomePage" value="~/HotelManager"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Home" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
<add namespace="HostelBookNow.Web.Helpers"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Any idea what wrong I might be doing that, application is still looking for the SQLExpress rather than my Server.
I am using ASP.NET MVC 3 app with Entity Framework 4.1.

Resources not always downloading in MVC3 application hosted in IIS 7.5

I have an MVC3 web application hosted in IIS 7.5 on Windows Server 2008 R2. The site is behind Windows Authentication; a logon prompt is shown when visiting the site. There is then a second level login using Forms Authentication. (The point is to hide the site from the public, etc..)
If I go to the site, pass the Windows Authentication login prompt, and then view the login page (Forms Authentication), some resource may or may not load. For instance, a CSS file or JavaScript file may not load. If I hit refresh (sometimes it takes a couple of times), the missing file is loaded okay. If I keep hitting refresh I can reproduce this error over and over. Sometimes all resources are loaded, other times they are not.
If I remove the Windows Authentication portion, the problem goes away - the site loads perfect every time.
I don't think it could be a permissions issue since the resources are
sometimes loaded properly.
It doesn't seem to be a caching issue because it happens before and after emptying my browser cache.
It's not a browser-specific issue because I've reproduced it in IE and Chrome.
Edit 1: When I view the resource which is apparently missing, in Chrome, I see that instead of the CSS or JavaScript content I expected, the login page is returned.
Edit 2: I've enabled anonymous access to the Css, Images and JavaScript folders which, of course, fixes the problem. I'd still like to know why the content sometimes came through and sometimes didn't.
Edit 3: Web.config is below. Please note, I am securing certain actions by adding [Authorize] to the controller or action. Everything else should be "open."
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<appSettings ... />
<connectionStrings ... />
<system.net>
<mailSettings>
<smtp ... />
</mailSettings>
</system.net>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880"/>
</authentication>
</system.web>
<system.webServer>
<defaultDocument enabled="true">
<files>
<clear />
<add value="Index"/>
</files>
</defaultDocument>
<validation validateIntegratedModeConfiguration="true"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<log4net xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
<file value="..\Logs\Web.txt"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="10MB"/>
<layout type="log4net.Layout.SimpleLayout"/>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
</configuration>
Since it sometimes worked, could it be that it worked when you were authenticated?
When a request fails verify that you are authenticated, so at least you can rule it out

Resources