Visual Studio debugging with windows auth not working - visual-studio

I have an ASP.NET webforms application that uses windows authentication when developing locally. The first time that I debug the webapp, IIS Express starts up and the pages work as expected. If I stop debugging and then start it again, I get in this endless cycle that no matter what page I go to, it always forwards to the login.aspx page and then to my Default.aspx page.
I can keep clicking on different pages, but it still keeps going to the Login then Default. I should be authenticated at this point and not be forwared to login.aspx. I believe it is because IIS express thinks that I am not authenticated. However, when I look at my cookies, I see that there is a ASP.NET_SessionId cookie so I don't think this should be happening.
If this helps, I have this in my page_load for login.aspx
if (authSection.Mode == AuthenticationMode.Windows)
{
//stuff happens here
Response.Redirect("Default.aspx");
return;
}
To fix the problem, I have to kill IIS express and start debugging again. I'm not really sure why it thinks that I am not authenticated. Even though this isn't the same question, I tried the answer provided here: https://stackoverflow.com/a/19515891/888617 and it did not help.

Edit: This actually doesn't appear to solve my issue.
It turns out the issue was specific to Chrome. I was getting this issue when debugging and had to kill the IIS express process for it to resolve itself. However, I found a more perminate solution by doing the following.
In %userprofile%\documents\IISExpress\config\applicationhost.config insure that the overrideModeDefault is set to allowed for windowsAuthentication and anonymousAuthentication like this:
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
<section name="windowsAuthentication" overrideModeDefault="Allow" />
Your authentication section should also look like this. Note the only provider is NTLM.
<authentication>
<anonymousAuthentication enabled="false" userName="" />
<basicAuthentication enabled="false" />
<clientCertificateMappingAuthentication enabled="false" />
<digestAuthentication enabled="false" />
<iisClientCertificateMappingAuthentication enabled="false">
</iisClientCertificateMappingAuthentication>
<windowsAuthentication enabled="true">
<providers>
<add value="NTLM" />
</providers>
</windowsAuthentication>
</authentication>
This section should also be in the web.config.
<authentication>
<windowsAuthentication enabled="true">
<providers>
<clear />
<add value="NTLM" />
</providers>
</windowsAuthentication>
</authentication>

Related

.Net Core 2.1 Error 413 on multipart/form-data POST only on IIS not IIS Express

I'm hitting a problem with multipart/form-data POST uploads on IIS. My client is an Angular SPA and my backend is on .Net Core 2.1 (I know it's old).
The backend project is published as Self-Contained win-x64. I'm not sure how it's configured exactly on IIS / Kestrel but the IIS App runs under a specific Application Pool (No managed Code / Integrated). My web.config looks like this:
<configuration>
<location path="." inheritInChildApplications="false">
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\my.app.exe" stdoutLogEnabled="false" stdoutLogFile=".\log\path" />
</system.webServer>
</location>
</configuration>
In my development environment instead I'm using IIS Expres.
Now I added a multipart/form-data upload, sending form data together with a blob/image. This worked out of the box in development settings. However when I publish to staging environment with real IIS and the above web.config, I always get 413 Request entity too large.
My controller looks like this:
[HttpPost]
[DisableRequestSizeLimit]
[RequestFormLimits(MultipartBodyLengthLimit = int.MaxValue, ValueLengthLimit = int.MaxValue)]
[RequestSizeLimit(int.MaxValue)]
[Route("my/route")]
public ActionResult MyHandler()
I also added limits for Kestrel in Program.cs:
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = 104857600; // 100MB
}
)
And to make the weirdness complete the 413 in staging environment only happens in Firefox. I have no idea what else I can do. I also cleared cache in firefox.
After longer search I finally found the necessary setting in IIS to make this work in Firefox. And it has indeed be mentioned in a few sources as the 'last option'. For me it was necessary in this case.
In 'IIS Manager' I selected the backend application and opened 'Configuration Editor'
system.webServer/serverRuntime -> uploadReadAheadSize=2147483647
That maked it work.

How do I debug AuthorizeAttribute and FormsAuthentication calls

I am having crazy problems with Forms Authentication, with the AuthorizeAttribute, and 302 redirect loops. I need to find out what is going on. Is there anyway I can debug Forms Authentication and the AuthorizeAttribute?
Just some more details, in case it is important:
I am using custom membership provider and role provider. I have the correct methods implemented and doing the reading for User/Roles from my custom database tables.
I have the following in my web.config to point to my custom providers:
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear />
<add name="MyMembershipProvider" type="Domain.Entities.Security.MyMembershipProvider" connectionStringName="MyDB" MinRequiredPasswordLength="8" MaxInvalidPasswordAttempts="5" MinRequiredNonAlphanumericCharacters="0" applicationName="My App Name" />
</providers>
</membership>
<profile enabled="false">
<providers>
<clear />
</providers>
</profile>
<roleManager enabled="true" defaultProvider="MyRoleProvider" cookieTimeout="2800" cookieSlidingExpiration="true" cacheRolesInCookie="true">
<providers>
<clear />
<add name="MyRoleProvider" type="Domain.Entities.Security.MyRoleProvider" connectionStringName="MyDB" applicationName="/" />
</providers>
</roleManager>
Some of my controller/actions are 'open'. Some of them have the 'Authorize[Roles="admin"]' and similar.
Sometimes I can work on the application for hours without anything happening. Sometimes I hit a 302 redirect loop soon after I login and then I try to go into one of the other pages. Once that happens, I cannot even go into the top level path without it going into a 302 redirect loop sometimes.
Any directions, any pointers, any suggestions would be greatly appreciated.
Please see the answer in the question linked. This was the resolution to the redirect loop problem.
IIS Session timeout and Forms Authentication loop

being redirected to wrong loginUrl -> account/login instead of account/LOGON

I have a strange error I have never run into before.
I secured a controller with:
[Authorize(Roles = "admin")]
public class LoggingController : Controller
When a non-admin user tries to access any protected content, they are redirected to:
http://localhost:50501/Account/Login?ReturnUrl=%2flogging
note: account/login and NOT account/logon
The AccountController.Login action does not exist.
web.config has:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
I can of course implement the Login action and redirect to Logon.
I am just puzzled and would like to know why this happens.
Search your project for login - it has to be specified somewhere. Is there any other web.config value overriding this (maybe looking at a child root and the parent value is being used)
Also is there any redirect that is happening? Are there any defaults set in your machine's web.config?
Is your default url on the project set to be a /login?
Install glimpse route debugger to see which route is being used for this page as well.
EDIT:
A little more research yields a known issue.
Check out this link:
ASP.NET MVC issue with configuration of forms authentication section
Theres a bug in mvc 3 beta - are you running the beta bits?
Also notice the mentioned item in the above url for RTM bits:
<add key="loginUrl" value="~/LogOn" />
Also check out
http://forums.asp.net/p/1616153/4138366.aspx
EDIT 2
Below is a solid comment about a potential source of this from #santiagoIT (upvote his comment please if the specifics help you)
Today I discovered the root of this problem: I had added 'deployable dependency' on 'ASP.NET Web Pages with Razor Syntax'. This adds a reference to: WebMatrix.Data.dll This assembly has a class with a static constructor that does the following: static FormsAuthenticationSettings(){ FormsAuthenticationSettings.LoginUrlKey = "loginUrl"; FormsAuthenticationSettings.DefaultLoginUrl = "~/Account/Login";} That explains!
This worked for me and I'm using MVC 3
<appSettings>
<add key="loginUrl" value="~/Account/LogOn" />
</appSettings>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" name=".ASPXFORMSAUTH" />
</authentication>
</system.web>
Also I found that adding the followinf part to the web config (only during debugging the config) helped speed up my debugging as had to authenticate for ANY page.
<authorization>
<deny users="?" /> <!-- remove after debugging -->
</authorization>
Just simply remove the WebMatrix dll if they are present in your deployed bin folder.
I fixed it this way
1) Go ot IIS
2) Select your Project
3) Click on "Authentication"
4) Click on "Anonymous Authentication" > Edit > select "Application pool identity" instead of "Specific User".
5) Done.

Html.Telerik().StyleSheetRegistrar() output file generating 404 message on asset.axd

I'm using the Telerik controls form MVC and they work great in my work/home dev environments, and in the work prod environment, but when I tried to deploy to my home prod environment (IIS7) I get a problem.
I've added the axd mime type, but wan't sure what else to do.
I read a post suggesting adding a handler, but wasn't sure if I'm setting that wrong or I'm just looking in the wrong direciton.
if you're on IIS7 make sure you add the handler to the <system.webServer><handlers> section:
<add name="MyName" path="MyName.axd" verb="*" type="NameSpace.Class, Assembly" />
I added: <add name="ScriptRegistrar" path="Access.axd" verb="*" type="Telerik.Web.Mvc.UI.ScriptRegistrar, Version=v2.0.50727" />
http://localhost:1000/asset.axd?id=sQAAAB-LCAAAAAAABADsvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee--997o7nU4n99__P1xmZAFs9s5K2smeIYCqyB8_fnwfPyJ-8UfT9qNHH7X5u_butGk-Gn10SX_u7ezujHfH93Ye0gfTjx619TqnX2YfPbr36f3RR_Tze7_4oxU1PKmWbb5s775ur8scb5_zV9VHj3ZGHy2pwbRaLKrlGKB_yYi_2JUv2rzM6-LtuN9gL2xwWTRtJt9__5d8_5f8PwEAAP__qtxwmrEAAAA%3d
To enable web resource combining with the Telerik Extensions you need to register the WebAssetHttpHandler in your webconfig:
IIS 7
<add name="AssetHandler" preCondition="integratedMode" verb="GET,HEAD" path="asset.axd" type="Telerik.Web.Mvc.WebAssetHttpHandler, Telerik.Web.Mvc"/>
IIS 6
<add verb="GET,HEAD" path="asset.axd" validate="false" type="Telerik.Web.Mvc.WebAssetHttpHandler, Telerik.Web.Mvc"/>
This handler enables you to use the Combine, Compress, and Cache features of the Script and StyleSheet Registrars. You can learn more and see additional config details in the Telerik online docs:
http://www.telerik.com/help/aspnet-mvc/web-assets-working-with-javascript-web-assets.html

Enabling FormsAuthentication for multiple subfolders in a site

We're trying to implement formsAuthentication on our site, but in a scenario that we haven't been able to find a solution for yet - other than creating our own HttpModule and doing the custom logic ourselves - so I thought I'd toss the question out there to see if this was indeed the only solution.
We'd like to use formsAuthentication on top of custom Membership providers, but would like to use a different provider for different folders. Our site partitions these sections with subfolders (eg: ~/Admin, ~/GoldCustomer, ~/SilverCustomer, ~/BronzeCustomer), so we'd like to use different Membership providers for each section/subfolder. Using the framework to support this, we'd implement our web.config like:
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<location path="Admin">
<system.web>
<authentication mode="Forms">
<forms name="AdminAuth" loginUrl="~/AdminLogin.aspx" />
</authentication>
<membership defaultProvider="AdminProvider" >
<providers >
<add connectionStringName="ConnString" name="AdminProvider" type="Assembly.AdminMembershipProvider" ... />
</providers>
</membership>
</system.web>
</location>
<location path="GoldCustomer">
<system.web>
<authentication mode="Forms">
<forms name="GoldCustomerAuth" loginUrl="~/GoldCustomerLogin.aspx" />
</authentication>
<membership defaultProvider="GoldCustomerProvider" >
<providers >
<add connectionStringName="ConnString" name="GoldCustomerProvider" type="Assembly.GoldCustomerMembershipProvider" ...="" />
</providers>
</membership>
</system.web>
</location>
<system.web>
<compilation debug="true" />
<authentication mode="Forms" />
</system.web>
</configuration>
Doing this though results in the runtime error:
It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.
Line 11: <location path="Admin">
Line 12: <system.web>
Line 13: <authentication mode="Forms">
Line 14: <forms name="FormsAdmin" loginUrl="~/login.aspx" />
Line 15: </authentication>
It seems that the only way to accomplish what we're trying is with a custom HttpModule - or change our approach (like breaking the folders up into different web apps in IIS). Is this correct, or am I missing something? Or are there other alternatives I'm not aware of?
Thanks for your help!
First of all, I think role-based security makes perfect sense for your application if you have control over the databases. But if you can't change it, it's a no-go.
The alternative solution can be a gateway login forms that redirects user to folder specific login form based on ReturnUrl querystring variable and that form will use the provider it wants to validate the user. Then it uses the FormsAuthentication.RedirectFromLoginPage to set an authentication cookie and redirect to the previous page. You can set the roles and use role based security to control access to each folder with <authorization> tag in web.config.
I'm not sure what you're trying to do but how about Roles for each of these customer types? Limit access by a role for each sub folder but you'd still have 1 membership provider and 1 role provider.

Resources