How does application Initialization in IIS work? - asp.net-mvc

I configured my IIS website to be always up and to initialize it after pool recycle. But I'm not sure how it works. This is .NET 6 MVC app.
All instructions say that I need to install Application Initialization role, but "Preload enabled" setting was available for my website even before installing this role. I set it to true but it didn't seem to work. I installed Application Initialization and it started working.
So the first question is what does "Preload enabled" setting do when you don't have Application Initialization installed?
I assume that with above settings IIS is making a request to my Home page. But I'm not sure I will have this page in final version of application.
The second question is, if I remove Home page will auto preloading stop working? If yes, then I need to use applicationInitialization settings in config file and configure it like this?
<add initializationPage="/CustomWarmupPage" hostName="myhost" />

So the first question is what does "Preload enabled" setting do when
you don't have Application Initialization installed?
Starting with IIS 8, application initialization is part of the IIS feature set. For IIS 7 and 7.5, it is available as a separate download through the Web Platform Installer. Application initialization with IIS 8 is an optional installation component in Windows or Windows Server Role Manager.
To support application initialization on your Web server, you must install the Application Initialization role or feature. If application initialization is not installed, the "Preload enabled" setting will have no effect.
The second question is, if I remove Home page will auto preloading
stop working? If yes, then I need to use applicationInitialization
settings in config file and configure it like this?
<add initializationPage="/CustomWarmupPage" hostName="myhost" />
The way this module works is that you introduce a path, and when your ApplicationPool runs, it sends a request to the registered path. System startup should not be delayed until the first request is sent to the program. To do this, you must enter the following command in the system.webServer tag of the web.config file,like:
<applicationInitialization doAppInitAfterRestart="true"
skipManagedModules="true" >
<add initializationPage="/default.aspx" />
</applicationInitialization>
Using the above command, we specify that after the ApplcationPool starts, it will send a "/default.aspx" request to the path entered in the initializationPage parameter, which is the initial setup of the service. Then you need to set the Application Pool Start Mode value to AlyawsRunning and the WebSite PreLoad Enebled value to true to do this automatically. This will always send a request to warm up the app when the app starts or restarts.

Related

IIS 8.5 - Application initialization not working

I have installed Application Initialization, set the website's application pool Start Mode to "Always Running", and set Preload Enabled = "True" in the advanced settings of the website.
However, if I recycle the application pool manually and wait 10 seconds, when I then reload the website, I still have to wait another 10 seconds for the website to warm up. This indicates that the website is not starting.
Looking at task manager, I can see that the application pool is running the whole time - even after a recycle. However, the memory usage is very low until I make my own request to the website.
One thing I have noticed is that I do not have a "Start Automatically" setting in the advanced settings of my website as per this link:
https://blogs.msdn.microsoft.com/vijaysk/2012/10/11/iis-8-whats-new-website-settings/
How can I get my application to auto-start?
It turned out to be a whole load of settings which all had to be correct. You go through all of the steps to install the relevant components and make the various config changes as per this link: http://www.iis.net/learn/get-started/whats-new-in-iis-8/iis-80-application-initialization
The key part which was missing for me was an instruction in the Web.config as below. I had it going to just "/Login" which is a valid route, but as soon as I switched it to "/[Controller]/[Action]" it worked.
The advantage of this route is that you can create a custom action which will also hit the database (initialising Entity Framework), and perform any other slow initialisation you wish. For me, I just read a record out of a DB table, so I get ASP.NET auto-starting, and also save the few seconds it takes to warm up EF too :)
<system.webServer>
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="false">
<add initializationPage="/Login/WarmUp" />
</applicationInitialization>
</system.webServer>
Try Application Initialization setup:
I had similar issues and tried very hard with IIS 8.5 Windows Server 2012 R2. Everything in the IIS was set correctly after referring to so many sites however had missed the Application Initialization setup. Refer to the below link, Setup section.
https://www.iis.net/configreference/system.webserver/applicationinitialization
There are multiple .config locations where these settings can be set.
Machine applicationHost.config (c:\windows\system32\inetsrv\Config)
Website web.config (c:\inetpub\wwwroot for Default Web Site)
Application web.config
I tried all but was only successful in configuring 3, the application web.config.
My specific use case was calling a GET method on a WCF service.
The steps for application initialization are found in the other answers too. Here is one that was most helpful. IIS 8.0 Application Initialization
Install the Windows feature Application Initialization (Web-AppInit)
Set the IIS app pool Start mode = AlwaysRunning
Set the IIS application Preload Enabled = true
Add to the application web.config
<system.webServer>
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="true">
<add initializationPage="/Service.svc/Method/Parameter" />
</applicationInitialization>
</system.webServer>
Recycle app pool
Check that the app initialized.
The thing I would like to point out is that the initialization page is relative to the application NOT to the root of the website/domain so if my absolute path is
domain.com/path1/path2/Service.svc
I would not include /path1/path2 in the initializationPage parameter.
These articles are very good:
Use IIS Application Initialization for keeping ASP.NET Apps alive
IIS 8.0 Application Initialization
However in my case there was a problem with installing the Application Initialization Role.
Check your IIS App's Modules listing. Ensure ApplicationInitializationModule is present.
I needed to uninstall/re-install this module.
I have no idea what happened as this appeared to work at first, then weeks later during development it stopped. No amount of tinkering/rework fixed it and I started to suspect I never actually saw this working.
Issue resolved upon uninstall/re-install Applicaion Initialization Module role.
If anyone's wondering what to do in MVC when you have multiple areas to initialise, you need to put the area at the start, all within the root web.config file. I was stuck for a while trying to put it in the area's web.config. Also it's perfectly compatible with hybrid applications.
<add initializationPage="/NotMVC.aspx" />
<add initializationPage="/Area1/Controller/Action" />
<add initializationPage="/Area2/Controller/Action" />

Deploying ASP MVC 5 App with IIS 7.5

I try to deploy ASP MVC 5 app in virtual directory (without creating new iis application)
I use IIS 7.5
I already put
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true" />
in web.config file.
But when i go to app url with IE browser it shows me just directory listing like in screenshot below
Is there a way to deploy MVC 5 in virtual directory and make it work like usual MVC application?
You need to convert the virtual directory to application. Right click on it in the IIS management console and choose Convert To Application.... Also make sure that the associated application is configured to use Integrated Pipeline Mode.
I solved this problem earlier in my production environment by checking the directory pointer in IIS. Apparently when I unzipped the deployed site from one server to the next, the zip utility made an extra level, so IIS was pointing to /MyProject when the files were in /MyProject/MyProject. I had a little better clue though, you have Document Browsing enabled based on that screen shot, make sure not to do that in production. I set the site to log custom errors and got a 403.14 response, from there found a blog on my mistake. You need to setup the environment to find the specific module that's failing, I think something to do with trace routes, idk. I'm a software developer that always gets forced into doing devOps; was googling my own problem and thought I'd throw you a line. Without a specific error message, all I can tell you is IIS is not connecting to .NET; something is not configured correctly. Turn off directory browsing, google how to get good error logs back, and let us know the status code so we can help you: 403.14, 401, 500, 404? Also give us the module that's failing. If it's the last one on the handler list, guess what, IIS isn't connecting to the app, which I suspect is your case.

IIS 7.5 with process idenity set to user has wrong USERPROFILE

First of all, this is my third question on the similar topic.. and still I have no answer, maybe only approaching it (see first, second).
My web application (ASP.NET MVC3 under IIS 7.5) runs git to access some github repositories. After I upgraded my workstation to Windows SP1 it stopped to work. The reason was that as soon as git started, it actually runs ssh.exe to communicate with github. The ssh.exe appears to hangs up, so all application hangs.
The application pool used by that application use the same process identity as myself. But using ProcessHacker I can see following picture:
Because of USERPROFILE is pointed to /system32/config/systemprofile ssh.exe is expecting to have .ssh folder, that contains public/private keys. Since keys are not there it hangs.
But keys are typically in ~/.ssh (in my case c:\users\alexander.beletsky.ssh). As soon as I copied keys into /system32/config/systemprofile application started to work as expected.
My question is, why does w3wp.exe thinks that its profile in /system32/config/systemprofile? is it possible to change that? it is expected behaviour for application pool or just issue of my machine?
Waiting for any clues!
EDIT
Load User Profile property of Application Pool is set to TRUE.
ssh.exe is actually using HOME environment variable. Check if it set correctly.
As my machine on which this works has the same value in enviroment page of process hacker, and still
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) has value of my user appData, and I have SP1, I think that it should not be related to it, but to something in your configuration that could have been changed. Check if your inetmgr has properly set identity for your application. Open C:\inetpub\temp\appPools\yourAppPoolName\yourAppPoolName.config and check if this setting exists:
<configuration>
....
<system.applicationHost>
<sites>
<site name="Default Web Site" id="1" serverAutoStart="true">
<application path="/yourAppPath" applicationPool="yourAppPoolName">
<virtualDirectory path="/" physicalPath="C:\inetpub\wwwroot\yourAppPath" userName="yourUserName" password="[enc:AesProvider:someHashHere=:enc]" />
</application>
...
</site>
</sites>
<system.applicationHost>
<configuration>
If not, you can configure it there (put password in plain text or you can configure it using inetmgr like I described in my answer to your other question).

Unable to get windows authentication to work through local IIS

So I've created a new ASP.NET MVC project using the intranet template. web.config contains the appropriate values (e.g. <authentication mode="windows"/>).
If I fire up the web app using the VS webserver, it all looks fine - the page shows my Windows domain and username and all. However, this works in Opera and Safari as well as IE and FF, which says to me it's not using Windows auth at all (since to the best of my knowledge this doesn't work in any browser except IE/FF).
Next step is to get it working through local IIS. I create a hosts file entry pointing www.mysite.mydomain to 127.0.0.1. So in IIS I create website with a binding to www.mysite.mydomain and enable Windows authentication and disable anonymous authentication.
I have set up IE and FF to enable Windows auth as follows:
IE
Add URL to intranet group
Ensure Windows auth is enabled in the advanced settings
FF
Put 'www.mysite.mydomain' into network.automatic-ntlm-auth.trusted-uris config setting.
But when I dial up www.mysite.mydomain in IE / FF I get a login prompt. Interestingly, even when I type in my Windows login here, it still fails and shows me the login prompt again.
We don't have active directory here but my understanding is that it should work fine with a local account.
I can't think of anything else I need to do. Any suggestions?
Edit: we've recently switched to using Active Directory and the problem remains.
Edit: when I cancel the login prompt, I get taken to an 'IIS 7.5 Detailed Error' page with the following information:
HTTP Error 401.2 - Unauthorized
You are not authorized to view this page due to invalid authentication headers.**
You have to whitelist a domain specified in the hosts file in order for windows authentication to work:
Click Start, click Run, type regedit, and then click OK.
In Registry Editor, locate the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters
Right-click Parameters, click New, and then click DWORD (32-bit) Value.
Type DisableStrictNameChecking and press ENTER.
Double-click the DisableStrictNameChecking registry value and type 1 in the Value data box, click OK
In Registry Editor, locate and then click the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
Right-click MSV1_0, point to New, and then click Multi-String Value.
Type BackConnectionHostNames, and then press ENTER.
Right-click BackConnectionHostNames, and then click Modify.
In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
Quit Registry Editor, and then restart the IISAdmin service.
NOTE:
The original Microsoft KB links on this answer were broken and have been removed.
This article provided the instructions for setting DisableStrictNameChecking.
I recently spent three days trying to solve the same problem and it drove me crazy. It was happening on a load-balanced setup where one of the servers was authenticating correctly while the other failed. Investigating the problem - and eventually solving it - it turned out to be unrelated to the load-balanced environment, it could happen with any server when authenticating using Windows Authentication and the server is called with a name other than the one recognized by Active Directory
1. Enable Kerberos logging
To correctly diagnose your issue, you will need to enable Kerberos logging on the machine hosting your IIS site. To do so, add the following registry entry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters
Add Registry Value LogLevel with ValueType REG_DWORD and value
0x1.
Once you turn on logging, then you try to authenticate, you will get errors logged in your Windows Application Log. You can ignore the error KDC_ERR_PREAUTH_REQUIRED (this is just part of the handshake) but if you get the error KDC_ERR_C_PRINCIPAL_UNKNOWN that means your AD controller doesn't recognize your server therefore you need to follow the steps below.
2. KDC_ERR_C_PRINCIPAL_UNKNOWN
if you're getting KDC_ERR_C_PRINCIPAL_UNKNOWN, that means the name "mysite.mydomain.com" is different from how the AD recognizes your machine so it's unable to provide a valid kerberos ticket. In that case, you need to register a Service Principal Name (SPN) for " 'www.mysite.mydomain" on the AD.
On your AD controller, run this command - you will need Domain Admin privilege:
Setspn -A HTTP/mysite.mydomain YOUR_MACHINE_HOSTNAME
3. Use a custom identity for your Application pool
Finally, make you Application pool use a custom account that belongs to the Active Directory instead of using NetworkService. This can be done in advanced settings of your application pool.
and .. voila.
Notes: The problem could (unlikely) be related to having multiple SPNs registered to the same machine, in that case you will need to run a command to remove duplicate SPNs, but I doubt this is the case. Also try adding a different binding to your site (that doesn't use a custom name) something like htttp://localhost:custom_port_number and see if authentication works. If it works, this is an extra indication that you're suffering from the same problem I had.
Did you try putting the domain in front of the user name?
DOMAIN\username
If you don't have a domain account, try prefixing your username with the machine name:
MYCOMPUTER\myusername
You should check to see if you have Windows Authentication installed/enabled. That may sound weird but in IIS 7 you have to install and enable the various authentication methods. Check out http://support.microsoft.com/kb/942043/ for more info, see quoted section below.
Cause 1
The Web application is configured to use Integrated Windows
authentication. However, the Windows Authentication feature is not
turned on. Or, the Integrated Windows authentication native module
section of the ApplicationHost.config file or of the Web.config file
is not valid. To resolve this problem, see Resolution 1.
Original
Usually when you try to view an asp.net web page hosted on IIS and receive a login prompt it doesn't mean your credentials weren't received or that you aren't authenticated. What it means is that the account that your website is running under doesn't have the right permissions to work with the files.
In IIS 6 and 7 you can easily change the user account that your app pool runs under. Try changing the app pool identity to an account with more access specifically designed for this. Or if you want to stick with the existing account (IUSR_? Network Service?) you can grant that account more permissions on the directory where your website is stored.
This article is specifically targeted at BizTalk but has almost no references to it and focuses on troubleshooting permissions issues with IIS and app pools: http://msdn.microsoft.com/en-us/library/aa954062.aspx
Why local IIS? Can you use local IIS Express?
If so, try this. It seems that IIS Express by default has Windows Authentication set to false.
Change
<windowsAuthentication enabled="false">
to "true" in applicationhost.config file (under 'C:\Users[Profile]\Documents\IISExpress\config' folder). This works for me.
To ensure that IIS uses Windows Authentication, I think you should try to turn of other authtentication methods. If Anonymous Authentication is enabled, Windows authentication will not work. You can also read this Microsoft Support Article which describes IE and IIS requirements in details.
I got this error when I enabled Windows authentication. I wanted to authorize the user based on Windows login and there is no login page in my application.
I got the error fixed by adding the below in my Web config file.
Under the tag system.web, I changed authentication mode="None" to
authentication mode="Forms".
Under the tag appSettings, I added add key="owin:AutomaticAppStartup" value="false"
After reading the answer of Espen Burud, I solved my problem by changing in the root's web.config:
<allow users="*" />
to
<deny users="?" />
The page that needs Windows Authentication is not in the root, but in a sub directory with its own web.config with deny users ? but that did not make Windows Authentication working. Apparently, you need to deny users in the root for that to work.
The IIS config has Anonymous Authentication enabled; that did not matter. After the above change of web.config, Windows Authentication worked.
For Dot Net Core 2.2 and running on IIS, I was having issues with 401.2 Unauthorized when I would check the Enable Windows Authentication within my application. It was a exceedingly simple test website that did basically nothing, just to try and get windows authentication to work. I finally got the auth to work, and here's what you'll need:
Within Startup ConfigureServices:
services.AddAuthentication(IISDefaults.AuthenticationScheme);
Open the application's Properties, click Debug option on the left and make sure you check Enable Windows Authentication.
But here's the kicker that I had forgotten... Configure your system to have Windows Authentication installed on IIS. This was never setup on my machine, and regardless what I did, I would always get a 401 unauthorized error. After installing this (Win 10, IIS v10.0.18362.1) I now get a login prompt. This isn't exactly what I need at this point, but at least it's not the unauthorized error. Good luck and hopefully this helps.

Asp.net mvc application deployment / security issues

I'll start with appologies; I wasn't sure if this was best posted here of Server Fault so if its in the wrong place then please move :-)
Basic information
I have written the first module of a new application at work. This is written using Visual Studio 2010, targetting .net 3.5 (at the moment) and asp.net mvc 2. This has been working fine during development running on the built in Development server from VS but however does not work once deployed to IIS 7/7.5.
To deploy the application, I have built it in release mode and created a deployment package by right clicking on the project in the solution explorer (this will be done with an automated build in tfs once upgrade from the beta). This has then been imported into IIS on the server.
The application is using windows/domain authentication.
Issue #1
I can fire up internet explorer and browse to the application from a client computer as well as on a remote desktop connection. I can execute the code which reads/stores data in Session fine from the IE instance on the remote desktop but if I browse to it from the client pc it seems to lose the session state. I click on the form submit and the page refreshes and doesn't execute the required code. I've tried setting with; InProc, SQLServer and StateServer. but with no luck :-(
Issue #2
As part of the application it views PDF and Tiff documents on the fly which are on a network share on the office network and creates thumbnails if the document hasn't been viewed before. This works if running on the machine the application is deployed to; however when browsing from a client pc I get an error saying:
Access to the path '\\fileserver\folder\file.tif' is denied
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.
Exception Details: System.UnauthorizedAccessException: Access to the path '\\fileserver\folder\file.TIF' is denied.
ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
As this is on a different server the user is not accessible. To get round this I have tried:
1 - setting the application pool to run as domain administrator (I know this is a security risk, but I'm just trying to get it to work at the moment!)
2 - to set the log on account for World Wide Web Publishing service to be the domain admin . When trying to restart the service I get ...
Windows could not start the World Wide Web Publishing Service service on the Local Computer.
Error 1079: The account specified for this service is different from the account specified fro the other services running in the same process.
Any pointers/help would be much appriciated as I'm pulling my hair out (of what little I have left).
Update
I've been using this funky little tool I found -
DelegConfig v2 beta (Delegation / Kerberos Configuration Tool). This has been really usefull. So I've got the accessing of the file share working (there is a test page which will read the files) so now I've just got the issue of passing through the users credentials through to the SQL Server (wans't my choice to do it this way!!) to execute the queries etc. but I can't get it to log on as the user. It tries to access it as "NT Authority\Network Service" which doesn't have a sql login (as should be the logged on user).
My connection string is:
<add name="User" connectionString="Data Source=.;Integrated Security=True" providerName="System.Data.SqlClient" />
No initial catalog is specified as the system is over multiple dbs (also wasn't my choice!!).
I really appriciate all the help so far! :-)
Any further hints?!
Issue #2 - Your options are:
Configure delegation (double-hop authentication) - I haven't done this on IIS7 and it's a bit different to 6, but I believe you will need to enable the web server machine account for delegation in AD, and create an SPN for the web server (eg setspn -A http/<Web Server FQDN> <Domain>\<Machine Name>). Troubleshooting Kerberos can be fairly painful.
Grant access to the network resources to the (domain) application pool account and make sure anonymous authentication is turned on ( <anonymousAuthentication enabled="true" userName="" defaultLogonDomain="" /> )
Response to Update:
You will need to make sure Kerberos authentication is working for SQL Server. Run the query select auth_scheme from sys.dm_exec_connections where session_id=##spid; it will return NTLM or KERBEROS. If it's NTLM, you'll need to do some work configuring SQL Server to use Kerberos. Set an SPN in AD for the SQL service account: setspn -A MSSQLSvc/<SQL Server FQDN>:1433 <Domain>\<Sql Service Account>, restart SQL Server and try the query again. You must use TCP/IP as the connection mechanism (this is the default).
If you don't have an initial catalog, you'll need to make sure that all of the user logins have a default database that they have access to. I would personally pick one database to be the initial catalog as you may get different behaviour depending on how the login is configured.
With this small part of information I could only give some hints:
Issue #1:
Maybe you have a misleading URL as action for the form? Or an caught&ignored exception? Do you have an onError-event in your global.asax.vb?
Sub Application_Error()
Dim ex As Exception = Server.GetLastError
' NOW HANDLE THE EXCEPTION --> REPORTING :-)
End Sub
Issue #2:
I recently had the same exception - I had to check the access-rights for users for this folder and set the appPool-identity to "NETWORKSERVICE". In your case you even try to access a network-folder - check the accessrights on the server and try to use the IP instead of the name - it could be a name-resolution-problem?!
Sorry for this small portion of information... This looks like problems only solveable with direct debug-options on the running server.
Finally last thing on Friday I got it working ...
As I said in the update, the tool for sorting out the delegation of credentials was very handy and helped no end to setting the correct SPN records.
I found I also had to set it up for SQL as I was passing through the credentials into the server. The other thing I found stopping the connections was some of the inbound windows firewall settings where causing problems.
For the connection string; I had to update to:
<add name="ConnectionStringName" connectionString="Data Source=.;Integrated Security=SSPI;Trusted_Connection=True" providerName="System.Data.SqlClient" />
Links I found useful:
Kerberos Authentication and SQL Server
DelegConfig
And even tho it mainly talks about Sharepoint ... this was also useful.
Hope this helps people in the future.

Resources