Read values of web.config file - asp.net-mvc

I want to read values of different sections of web.config files.
for e.g.
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" requestValidationMode="4.5"
maxRequestLength="102400" />
<pages validateRequest="true"></pages>
</system.web>
In this system.web section I want to read httpRuntime requestValidationMode
value. In pages I want to read value for validateRequest.
Also, I want to read values of custom headers
<httpProtocol>
<customHeaders>
<add name="X-Content-Type-Options" value="nosniff" />
<add name="X-Frame-Options" value="SAMEORIGIN" />
<remove name="X-Powered-By" />
<add name="X-XSS-Protection" value="1; mode=block" />
</customHeaders>
</httpProtocol>

I believe you want something like this
ConfigurationSection httpProtocolSection =
ConfigurationManager.GetSection("system.webServer/httpProtocol");
ConfigurationElementCollection customHeadersCollection = httpProtocolSection.GetCollection("customHeaders");
For the other values, you have to search for where that value is stored. For example
<compilation debug="true" ...>
is stored here
HttpContext.Current.IsDebuggingEnabled
Many of the section types, additionally, are stored in System.Web.Configuration
System.Web.Configuration.PagesSection
System.Web.Configuration.HttpHandlersSection
And you can retrieve those with GetSection() as well.

Related

Why do I still get "A potentially dangerous Request.Form value was detected" even after disabling it?

I've just created a new MVC4 "Internet" application in Visual Studio 2012 (C#).
I went to the default /Account/Login page and typed in <b /> as the username.
The server crashed with this error:
A potentially dangerous Request.Form value was detected from the client (UserName="").
I've seen it before and got rid of it before, so I can do it again easily. I changed my Web.config to look like this:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" requestValidationMode="2.0" /><!-- Look here -->
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages validateRequest="false"><!-- Look here -->
<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.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
I cleaned the solution and did a rebuild, but I still get exactly the same error when I try <br /> again.
What's wrong?
Modifying the Web.config file is how you would disable the setting in Web Forms.
In MVC you would apply the ValidateInput attribute to your controller method.
<HttpPost>
<ValidateInput(False)>
Public Function ActionName(model As Object) As ActionResult
End Function
Or if you prefer C#
[HttpPost]
[ValidateInput(false)]
ActionResult ActionName(Object model) {
}

<IndexUserFields> fields haven't been indexed

I'm working on an Umbraco project.
I'm using a StandardAnalyzer indexer and I've just added an ArabicAnalyzer indexer.
The fields under <IndexUserFields> haven't been indexed.
part of my ExamineIndex.config file:
<IndexSet SetName="ArabicIndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/Arabic/" >
<IndexAttributeFields>
<add Name="id" />
<add Name="sortOrder"/>
<add Name="nodeName" EnableSorting="true"/>
</IndexAttributeFields>
<IndexUserFields>
<add Name="_AllContents"/>
<add Name="cityName"/>
<add Name="countryName"/>
</IndexUserFields>
<IncludeNodeTypes>
<add Name="Country" />
<add Name="DestinationInfoTopic" />
<add Name="Article" />
</IncludeNodeTypes>
</IndexSet>
All <IndexAttributeFields> fields are indexed, but <IndexUserFields> aren't, BTW the same fields are indexed using StandardAnalyzer.
Do I need to do something extra in order to index these fields?
After hours of digging finally I found an answer to my problem.
Due to our ArabicAnalyzer usage we must add the indexSet name to the Indexer provider:
<add name="ArabicIndexer"
type="UmbracoExamine.UmbracoContentIndexer, UmbracoExamine"
supportUnpublished="false"
supportProtected="false"
interval="15"
analyzer="Lucene.Net.Analysis.AR.ArabicAnalyzer, Lucene.Net.Contrib.Analyzers"
indexSet="ArabicIndexSet" />

Restrict access to ELMAH using custom RoleProvider

in my mvc-project i have set up ELMAH for the exception-handling. ELMAH comes with a frontend which can be accessed by "/elmah.axd".
In the web.config this is configured like this:
<location path="elmah.axd">
<system.web>
<httpHandlers>
<add verb="POST,GET,HEAD"
path="elmah.axd"
type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<authorization>
<allow roles="ADMIN" /> <!-- instead i want to use 'permission' from my custom RoleProvider -->
<deny users="*"/>
</authorization>
</system.web>
<system.webServer>
<handlers>
<add name="ELMAH"
verb="POST,GET,HEAD"
path="elmah.axd"
type="Elmah.ErrorLogPageFactory, Elmah"
preCondition="integratedMode" />
</handlers>
</system.webServer>
</location>
If i would use the standard RoleProvider i would use the authorization as specified in the example above. But as i have a custom RoleProvider i can't / dont know how to do this.
For my Views i have implemented a custom Authentication-Attribute which is very similar to the [Authorize] Attribute (but takes Permissions instead...). Now i want to specify the accessibility for "elmah.axd" (which is no physical file) using my custom RoleProvider.
Does anyone have a clue how i could archieve my goal?
here seems to be a viable approach...

Setting up SimpleMembership in MVC4

I am reading that in MVC4 to set up simple membership I should do this step:
In the AppSettings include a line:
<add key="enableSimpleMembership" value="true" />
However when I look at the samples generated from the templates they only have:
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
So why do I keep reading it's necessary to set the enableSimpleMembership key?
By default the SimpleMembershipProvider is enabled when you create a new ASP.NET MVC 4 application. But some hosting providers might disable it by overriding this setting in a higher level web.config.
Quote from an article about SimpleMembership:
If you see an error that tells you that a property must be an
instance of ExtendedMembershipProvider, the site might not be
configured to use the ASP.NET Web Pages membership system
(SimpleMembership). This can sometimes occur if a hosting provider's
server is configured differently than your local server. To fix this,
add the following element to the site's Web.config file:
<appSettings>
<add key="enableSimpleMembership" value="true" />
</appSettings>
This setting is used by the WebMatrix.WebData.PreApplicationStartCode method which executes automatically when your site runs and will use the value of this setting to enable the simple membership provider.
Actually configuring the SimpleMembershipProvider explicitly is what I would recommend you:
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider"
type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear/>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
Now, there's no room for confusion anymore. Both the membership and role providers are configured explicitly.

Exclude specific path from WIF authorization in a ASP.NET MVC 4 project

We have successfully configured windows identity foundation (WIF) in our ASP.NET 4.5 MVC 4 project with the help of the Identity and Access... extension for Visual Studio 2012. But are unable to exclude a specific path from authorization to allow anonymous access.
When we access our default route (i.e. /Home), the passive redirection will redirect us to the configured issuer Uri. This is currect. But now assume we want to exclude Path /Guest from STS Authentication so that everybody can access http://ourhost/Guest without beeing routed to the STS issuer. Only static documents are located there.
Snippets from Web.config:
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="http://ourhost/" />
</audienceUris>
<issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<trustedIssuers>
<add thumbprint="9B74****40D0" name="OurSTS" />
</trustedIssuers>
</issuerNameRegistry>
<certificateValidation certificateValidationMode="None" />
</identityConfiguration>
</system.identityModel>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="false" />
<wsFederation passiveRedirectEnabled="true" issuer="http://oursts/Issue" realm="http://ourhost/" reply="http://ourhost/" requireHttps="false" />
</federationConfiguration>
</system.identityModel.services>
Further we have...
<system.webServer>
<!-- ... -->
<modules runAllManagedModulesForAllRequests="true">
<add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
and finally:
<system.web>
<!-- ... -->
<authentication mode="None" />
</system.web>
We tried the following without success:
<location path="~/Guest"> <!-- also "/Guest" is not working -->
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
We also tried to put a small Web.config file into this folder, without success. No matter which Uri we locate to in the browser, we're always redirected.
What is the proper way to accomplish this?
EDIT
Removed the previous "accepted answered", set "accepted answer" to Eugenios answer as this is the more useful reply.
In an MVC app you typically define access through the [Authorize] attribute in controllers and actions.
Just remove from web.config:
<system.web>
<authorization>
<deny users="?" />
</authorization>
Note: this is usually added automatically by the "Add STS Reference" wizard in VS2010
It seems that the behaviour is exactly the same on VS2012 and the new tools. I just created a brand new MVC4 app. Ran the "Identity and Access..." tool with a local config STS (left all defaults).
It did add this fragment to the web.config:
<authorization>
<deny users="?" />
</authorization>
I removed it and added [Authorize] to the About controller action:
[Authorize]
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
When I click on the "About" link, then I get redirected to the STS. Everything else works with anonymous access.
Note:
You have some control on this too in the wizard (see the "Configuration" page of the wizard).
I can not get [Authorize] to work - it is not doing the redirect to my STS, and I am sure it is something I am missing. I did discover how to solve for the original ask, though.
In global.asax:
protected void Application_Start()
{
... config stuff ...
FederatedAuthentication.WSFederationAuthenticationModule.AuthorizationFailed += WSFederationAuthenticationModule_AuthorizationFailed;
}
and then:
void WSFederationAuthenticationModule_AuthorizationFailed(object sender, AuthorizationFailedEventArgs e)
{
// Do path/file detection here
if (Request.Path.Contains("/Content/") || Request.Path.Contains("/Scripts/"))
{
e.RedirectToIdentityProvider = false;
}
}
I was in the same situation as Thomas. In my case, I was testing/using IISExpress locally.
Eugenio's answer almost got me working, with one added requirement. I had to set the "Anonymous Authentication" in my MVC Project Property to "Enabled."
This was either disabled by default or possibly set that way when using the VS 2012 "Identity and Access..." tooling.
So, to recap, there was no code or special attributes to write/maintain.
My csproj file contains:
<IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
My web.config contains:
<system.web>
<authentication mode="None" />
</system.web>
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
</modules>
</system.webServer>
<system.identityModel.services>
<federationConfiguration>
<wsFederation passiveRedirectEnabled="true" issuer="https://REMOVED.accesscontrol.windows.net/v2/wsfederation" realm="urn:REMOVED" requireHttps="false" />
</federationConfiguration>
</system.identityModel.services>
And, I add the standard [Authorize] attribute to controller actions that I want to be defended by WIF:
[Authorize]
public ActionResult About()
{
....
}
What finally pointed me into the right direction was an older blog post which explains how to protect a specific controller or area of the page. In combination with global filters I'm almost there.
It seems like the key is not to use the passiveRedirectEnabled="true" option but set it to false. Only then you have the full control over the authentication process, but would need to trigger the passive redirection yourself then, using the SignInRequestMessage class (which is not a big deal).
Better solutions with less code required are welcome.
EDIT
Removed "accepted answered" state for this, set "accepted answer" to Eugenios anwer as this is the more useful reply.
I solved this in the web.config, the firts line Allow all unauthorized users and the second line disabled redirection
<wsFederation passiveRedirectEnabled="false" issuer="xxx" realm="xxx"/>
<authentication mode="Windows" />
<authorization>
<allow users="*" />
</authorization>

Resources