Flask Web App with Windows Authentication - windows

I have Flask app on IIS similiar to this tutorial : https://medium.com/#nerdijoe/how-to-deploy-flask-on-iis-with-windows-authentication-733839d657b7 but I'm using httpPlatformHandler instead of FastCGI.
With web.config as below I get None in REMOTE_USER :
request.environ.get('REMOTE_USER')
web.config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" />
</handlers>
<httpPlatform stdoutLogEnabled="true" stdoutLogFile=".\python.log" startupTimeLimit="20" processPath="C:\python3\python.exe" arguments="-m flask run --port %HTTP_PLATFORM_PORT%">
</httpPlatform>
<httpErrors errorMode="DetailedLocalOnly" />
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
</configuration>
How to get username of a user logged to a site using Flask on IIS?

Related

Why does the name of my Publish Profile affect the transformation of my Web.config?

I think I have encountered a strange interaction where the name of my Publish Profile is affecting the contents of the published Web.config.
For context, I have 2 solution configurations; Release & Staging, and a folder Publish Profile called 'Release.pubxml'. Below are stripped down versions of the three web configs involved.
Web.config:
<configuration>
<connectionStrings>
<add name="DBEntities" connectionString="{Web.config connection string}" />
</connectionStrings>
<appSettings>
<add key="WEBSITEURL" value="http://website.com" />
<add key="ADMINURL" value="http://admin.website.com" />
</appSettings>
</configuration>
Web.Release.config:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add xdt:Transform="SetAttributes" xdt:Locator="Match(name)" name="DBEntities" connectionString="{Web.Release.config connection string}" />
</connectionStrings>
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>
<system.webServer>
<rewrite xdt:Transform="Insert">
<rules>
<rule name="HTTPtoHTTPSredirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Web.Staging.config:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add xdt:Transform="SetAttributes" xdt:Locator="Match(name)" name="DBEntities" connectionString="{Web.Staging.config connection string}" />
</connectionStrings>
<appSettings>
<add xdt:Transform="SetAttributes" xdt:Locator="Match(key)" key="WEBSITEURL" value="http://stagingwebsite.com" />
<add xdt:Transform="SetAttributes" xdt:Locator="Match(key)" key="ADMINURL" value="http://admin.stagingwebsite.com />
</appSettings>
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>
</configuration>
I had recently adjusted our Staging web config, and tried publishing under the Release.pubxml profile, but with the Configuration set to Staging, rather than Release. The result I expected was the original Web.config file, with all Web.Staging.config xdt transformations applied.
What ended up happening was a Frankenstein mix of the Web.Staging.config and the Web.Release.config transforming into Web.config:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add xdt:Transform="SetAttributes" xdt:Locator="Match(name)" name="DBEntities" connectionString="{Web.Release.config connection string}" />
</connectionStrings>
<appSettings>
<add xdt:Transform="SetAttributes" xdt:Locator="Match(key)" key="WEBSITEURL" value="http://stagingwebsite.com" />
<add xdt:Transform="SetAttributes" xdt:Locator="Match(key)" key="ADMINURL" value="http://admin.stagingwebsite.com />
</appSettings>
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>
<system.webServer>
<rewrite xdt:Transform="Insert">
<rules>
<rule name="HTTPtoHTTPSredirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
You'll notice it has the Release connection string, the Staging WEBSITEURL/ADMINURL, and the Release HTTP rules.
I could not find any trace of the Release configuration anywhere in my settings. I had checked the configuration manager and all projects were set to build as Staging & I had cleaned/rebuilt multiple times. I had also tested it with both VS 2022 & VS 2019, and with multiple, separate solutions; each yielded the same result.
What ended up "fixing" it, was changing the name from 'Release.pubxml' to anything but Release.pubxml or Staging.pubxml. Although you wouldn't usually want to name your publish profile anything outside of what its configured to, why does the name of the publish profile override the configuration build you have set? With some further investigation, it seems that it might be transforming the chosen configured build first (Staging), then it transforms any config with the same name as your publish profile (Release).
This interaction seems extremely dangerous to me, so would anybody be able to explain to me why Visual Studio would do this (or if I have maybe encountered a bug)?

web.config gets modified when published

I have an asp.net web application and everything is working correctly. Now I wanted to upload another app on a subdomain of my server and to run both I have to change hostingModel from "inprocess" to "outofprocess".
So I modified my web.config to
?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\AmsWebApp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="outofprocess" />
</system.webServer>
</location>
</configuration>
<!--ProjectGuid: XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX-->
I found out that when I publish my application the original web.config file from the bin\Release\net6.0 folder gets deleted and a new and different one is appearing in the obj\Release\net6.0\PubTmp\Out folder looking like that
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\AmsWebApp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
Why is this happening and what do I have to do to avoid this?
Many thanks
I got some feedback from my server host telling me to update the .csproj file with following addon
<PropertyGroup>
<AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
</PropertyGroup>
and now all is working as supposed.

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?

Telerik RadControls setup issue

I just ran the Telerik update wizard for Teleriks RadControls for ASP.NET because for some reason my web.config was not setup to run RadControls. It modified my web.config. I am not getting the following error:
ASP.NET Ajax client-side framework failed to load.
If i revert my web.config back to the backup i get this error:
'~/Telerik.Web.UI.WebResource.axd' is missing in web.config. RadScriptManager requires a HttpHandler registration in web.config. Please, use the control Smart Tag to add the handler automatically, or see the help for more information: Controls > RadScriptManager
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.InvalidOperationException: '~/Telerik.Web.UI.WebResource.axd' is missing in web.config. RadScriptManager requires a HttpHandler registration in web.config. Please, use the control Smart Tag to add the handler automatically, or see the help for more information: Controls > RadScriptManager
If i refrain from using the RadScriptManager and revert back to using a normal ScriptManager, my project works fine. Except on some pages when i operation is performed i receive the following error:
Sys.InvalidOperationException: A control is already associated with the element.
The above error was why i attempted to us the RadScriptManager in the first place...
Has anyone run into this issue before and perhaps know what is going on?
D
the handler is not registered correctly. Click on the smart tag of the RadScriptManager and choose "register"
or copy the settings from this web.config file (.net45)
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="Telerik.ScriptManager.TelerikCdn" value="Disabled" />
<add key="Telerik.StyleSheetManager.TelerikCdn" value="Disabled" />
</appSettings>
<system.web>
<compilation debug="false" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
<pages>
<controls>
<add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI" />
</controls>
</pages>
<httpHandlers>
<add path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" validate="false" />
<add path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" validate="false" />
<add path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" validate="false" />
<add path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" validate="false" />
<add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false" />
</httpHandlers>
<httpModules>
<add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" />
<add name="RadCompression" type="Telerik.Web.UI.RadCompression" />
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="RadUploadModule" />
<add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" preCondition="integratedMode" />
<remove name="RadCompression" />
<add name="RadCompression" type="Telerik.Web.UI.RadCompression" preCondition="integratedMode" />
</modules>
<handlers>
<remove name="ChartImage_axd" />
<add name="ChartImage_axd" path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" preCondition="integratedMode" />
<remove name="Telerik_Web_UI_SpellCheckHandler_axd" />
<add name="Telerik_Web_UI_SpellCheckHandler_axd" path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" preCondition="integratedMode" />
<remove name="Telerik_Web_UI_DialogHandler_aspx" />
<add name="Telerik_Web_UI_DialogHandler_aspx" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" preCondition="integratedMode" />
<remove name="Telerik_RadUploadProgressHandler_ashx" />
<add name="Telerik_RadUploadProgressHandler_ashx" path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" preCondition="integratedMode" />
<remove name="Telerik_Web_UI_WebResource_axd" />
<add name="Telerik_Web_UI_WebResource_axd" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" preCondition="integratedMode" />
</handlers>
</system.webServer>
</configuration>

Resources