forms authentication, not able to save web.config programmatically - asp.net

im using visual studio 2008. in my project im using forms authentication, my project structure is as follows
root
|
login.aspx
home.aspx
web.config
admin (folder)
|
admin.aspx
web.config
here in root web.config is as follows
<authentication mode="Forms">
<forms name="Authen" protection="All" timeout="60" loginUrl="Login.aspx" enableCrossAppRedirects="true" cookieless="AutoDetect"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
and in inner web.config
and my users are
Username Role
admin1 Admin
admin2 Admin
user1 User
user2 User
as you can see that in second web.config, i gave access to users with "Admin" role and "user1" user.
for giving access to "admin" folder, i wrote the following:
Configuration config = WebConfigurationManager.OpenWebConfiguration("~/HR");
SystemWebSectionGroup systemWeb = (SystemWebSectionGroup)config.GetSectionGroup("system.web");
AuthorizationSection section = (AuthorizationSection)systemWeb.Sections["authorization"];
AuthorizationRule newRule = new AuthorizationRule(AuthorizationRuleAction.Allow);
newRule.Users.Add("user1");
section.Rules.Add(newRule);
and saved the web.config as
config.Save();
this is working fine when i run it from visual studio development server, when i host it in IIS, im getting the following error
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: An error occurred loading a configuration file: Access to the path 'F:\dotnet\samples\myproj\UI\hr\f-q_g-yn.tmp' is denied.
Source Error:
[No relevant source lines]
Source File: F:\dotnet\samples\myproj\UI\hr\web.config Line: 0
here the problem is, it is not able to save the web.config
i got one solution, that is, i added
<identity impersonate="true" userName="myusername" password="mypassword"/>
to root web.config and it is working fine. but my boss says that is not the correct way. what is the correct way to solve this problem ??
please help

The account your website is running under does not have permissions to write to the directory your web.config is in. There are two options how to solve that:
Run your website under another account which does have the required permissions. You set the account in the settings of the respective Application Pool in IIS Manager.
Modify the security settinsg (ACLs) of the directory/directories, and add write permissions for the user your application pool is running under.
You should probably combine both methods – use a separate user account and add the write permissions only to this account, not to e.g. Network Service.
(But note that I am not sure whether a website modifying its own web.config files is a good idea at all.)

Related

An error occurred while accessing the resources required to serve this request.

I am trying to setup an asp.net website in localhost. Fitst, I enabled IIS server and created website in
C:\inetpub\wwwroot folder and ran to ensure IIS is properly setup. In this case I used a existing website I created from visualstudio IDE. Everything was perfect. In this case I heavily used the following article.
http://forums.asp.net/t/1689133.aspx
Now the problem is I have a web site I downloaded from a remoteserver and I want to host it in localhost.
When I compare the site I downloaded and the working site, I noticed that some files are missing. Howevere, the site in remote sever is working properly.
I didnt see a bin folder and there is no much information on web.config file.
Here is the code in web.config file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
When I try to do the same process I did for the previous website and tried the browser then I get following erro.
Access is denied.
Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.
Error message 401.2.: Unauthorized: Logon failed due to server configuration. Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server. Contact the Web server's administrator for additional assistance.
Where is the error ? How to fix this issue? If you want more information let me know?
I would suggest you to first allow all users in WebConfig
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
EDIT : As Mentionned by David Thompson, this is highly insecure. Use this only to unblock your test sample code scenario. Never in Production, please.
This is an old question but the answer is seriously insecure, you should add and enable the authentication provider that you require rather than giving anyone authorization.
To add the provider:
https://www.iis.net/configreference/system.webserver/security/authentication/windowsauthentication/providers/add
To enable the method:
Open the IIS Management Console on the web server
Expand the Sites folder
Double-Click the IIS - Authentication option
Under Authentication, select the Anonymous Authentication and click 'Disable' in the Actions pane on the right
For Windows Authentication: Select the Windows Authentication and click 'Enable' in the Actions pane on the right
For Basic Authentication: Select the Basic Authentication and click 'Enable' in the Actions pane on the right
What solved this for my was enabling 32-bit applications in the app pool's advanced settings.
Open IIS
Expand server and click Application Pools in the Connections pane
Select your application pool and click Advanced Settings...
Under General switch Enable 32-Bit Applications to True

Configuration file cannot be accessed, insufficient permissions

I apparently, according to this error, cannot access my site:
Cannot read configuration file due to insufficient permissions
which basically means it cannot access my web.config file due to it not having permission to do so.
I tried goint to control panel->programs->turn windows features on/off->IIS->ADF->click ASP.net
and yet I still do not have access to my configuration file.
How can I tell IIS to give permission to this file? I am running version 7 on windows 7 64bit if that helps.
In web.config insert
<authentication mode="Forms">
<allow users="*"/>
</authentication>
This gives everybody permission to view your site

Error in web.config "location"

My site has 2 logins. 1 on the front end for regular users, and one in the admin section, for admins (I need 2 logins because each one asks for different login criteria). To authenticate the admin directory, I setup a "location" element in my main site's web.config like this:
<location path="Admin">
<system.web>
<authentication mode="Forms" >
<forms loginUrl="/Accounts/adminLogin.aspx"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
If I try to type any page from my "Admin" directory, into my browser, I get the following 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.
How can I setup my location element to redirect properly?
Thanks
There are mainly one of the two reason why you got this error message.
If you have not configured your asp.Net application in iis. If you have not configure your application to run on iis first configure your site to run on iis.For that create virtual directory from iis and give permission to application (read,write)
If above is not problem then there are mainly problem of two or many web.Config exists on your site.When you open some site and if software crate backup of that application then software mainly do create subfolder and copy all files + web.Config in application.Just remove this subfolder web.Config from subfolder.
Check the web.Config in your admin folder and main root folder for settings and configurations.
You can't change the Authentication mode within a subdirectory. Only WebApplications can define this setting which applies to the entire application. A location element is only used in subdirectories to change authorization, not authentication settings.

Permissions required to use Microsoft.Web.Administration

I'm trying to use IIS 7 management API but stuck with a security issue. My application is regular ASP.NET site running on .NET 4 (integrated pipeline). The machine is Windows 7 x64 (the app pool is default, running under ApplicationPoolIdentity, x64). The site uses the following settings:
<identity impersonate="true" />
<authentication mode="Windows" />
<customErrors mode="Off" />
<authorization>
<deny users="?" />
</authorization>
My site tries to read other site's details via IIS management API (at localhost). I'm logged in as a member of local Administrators. In IE i try to open my page but get this:
Site 'mysite' at 'myhost' is unknown.System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at Microsoft.Web.Administration.Interop.IAppHostProperty.get_Value()
at Microsoft.Web.Administration.ConfigurationElement.GetPropertyValue(IAppHostProperty property)
at Microsoft.Web.Administration.Site.get_State()
I don't understand why. I'm damn sure the code runs in impersonation context of my account (can see this is debugger watching System.Threading.Thread.CurrentPrincipal). What am i doing wrong?
p.s.
UAC is on, but i believe that's not important.
Checked NTFS permissions on C:\Windows\system32\inetsrv\config folder - full access for Administrators.
UAC is indeed the root of all evil. Impersonation behavior is broken when it's on. Something is really over-complicated here :(
When UAC is enabled and the current security context is impersonated, the principal reports he's not a member of local Administrators group. But he is. It has something to do with interactive/non-interactive sessions.
Try set temp directory into web.config to folder with full permissions.
<compilation tempDirectory="c:\temp" ... ></compilation>

How to resolve "Server Error in '/' Application" error?

I am trying to deploy an asp.net application in our server while I am receiving the following error.
Server Error in '/' Application.
________________________________________
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: 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.
Source Error:
Line 63: ASP.NET to identify an incoming user.
Line 64: -->
Line 65: <authentication mode="Windows"/>
Line 66: <!--<forms loginUrl="~/SCR.UI/Login1.aspx"/>
Line 67: </authentication>-->
Source File: D:\BarclaysPayamentManagementSystem\scr.ui\web.config Line: 65
What is the reason and how to resolve it?
Please help
You may get this error when trying to browse an ASP.NET application.
The debug information shows that "This error can be caused by a virtual directory not being configured as an application in IIS."
However, this error occurs primarily out of two scenarios.
When you create an new web application using Visual Studio .NET, it automatically creates the virtual directory and configures it as an application. However, if you manually create the virtual directory and it is not configured as an application, then you will not be able to browse the application and may get the above error. The debug information you get as mentioned above, is applicable to this scenario.
To resolve it, right click on the virtual directory - select properties and then click on
"Create" next to the "Application" Label and the text box. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.
When you have sub-directories in your application, you can have web.config file for the sub-directory. However, there are certain properties which cannot be set in the web.config of the sub-directory such as authentication, session state (you may see that the error message shows the line number where the authentication or session state is declared in the web.config of the sub-directory). The reason is, these settings cannot be overridden at the sub-directory level unless the sub-directory is also configured as an application (as mentioned in the above point).
Mostly, we have the practice of adding web.config in the sub-directory if we want to protect access to the sub-directory files (say, the directory is admin and we wish to protect the admin pages from unauthorized users).
I had this error when the .NET version was wrong - make sure the site is configured to the one you need.
See aspnet_regiis.exe for details.
I had this error with VS 2015, in my case going to the project properties page, Web tab, and clicking on Create Virtual Directory button in Servers section solved it
It sounds like the admin has locked the "authentication" node of the web.config, which one can do in the global web.config pretty easily. Or, in a nutshell, this is working as designed.
I just had the same issue on visual studio 2012. For a internet application project.
How to resolve “Server Error in '/' Application” error?
Searching for answer I came across this post, but none of these answer help me.
Than I found another post here on stackoverflow that has the answer for resolving this issue.
Specified argument was out of the range of valid values. Parameter name: site
When you create an new web application using visual studio.net, it automatically creates the virtual directory and configures it as an application. However, if you manually create the virtual directory and it is not configured as an application, then you will not be able to browse the application and may get the above error.
I also got this error when I moved an entity framework edmx file into a "Models" sub-folder. This automatically changed the metadata in my connection string setting in my app.config.
So before the connection string changed... it looked something like this:
<connectionStrings>
<add name="MyDbEntities" connectionString="metadata=res://*/MyDb.csdl|res://*/MyDb.ssdl|res://*/MyDb.msl; ...
</connectionStrings>
And after... it added the "Models" subfolder name (btw... it also added "Models" to the namespace for the EF classes generated) and the connection string now looks something like this:
<connectionStrings>
<add name="MyDbEntities" connectionString="metadata=res://*/Models.MyDb.csdl|res://*/Models.MyDb.ssdl|res://*/Models.MyDb.msl; ...
</connectionStrings>
I have a website project that references this Entity Framework DB project. But its web.config did not have the updates to the connection string... and that's when I started getting the compilation error being discussed here.
To fix this error, I updated the connection string in the web.config in the website project to match the app.config in my EntityFramework project.
vs2017 just added in these lines to csproj.user file
<IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
<IISExpressUseClassicPipelineMode>false</IISExpressUseClassicPipelineMode>
with these lines in Web.config
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" />
<identity impersonate="false" />
<authentication mode="Windows" />
<authorization>
<allow users="yourNTusername" />
<deny users="?" />
</authorization>
And it worked
I opened the Properties window for the website project in question and changed Windows Authentication to "Enabled" and that resolved my issue in VS 2019.
The error message is quite clear: you have a configuration element in a web.config file in a subfolder of your web app that is not allowed at that level - OR you forgot to configure your web application as IIS application.
Example: you try to override application level settings like forms authentication parameters in a web.config in a subfolder of your application

Resources