We have asp.net MVC & angular application. We are using identityserver3 for access control to the application.
Everything is working as expected, except one thing.
Unauthorized users still have access to static content of the application.
Is there any way to deny access to those files before user log in ?
Here is the link to the great post which led me to the solution => Intercepting file requests
Steps I've taken to solve my problem:
Added this line to my webconfig file.
This will make sure that js files request wil not be processed by handler.
<system.webServer>
<handlers>
<add name="JSFileHandler" path="*.js" verb="GET"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Register route.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.RouteExistingFiles = true;
routes.MapRoute(
"staticfiles"
, "{*src}"
, new { Controller = "Main", action = "GetJS" }
, new { src = #"(.*?)\.(js)" } // URL constraints
);
Return file from controllers action
public ActionResult GetJS()
{
var path = this.Url.RouteUrl("staticfiles");
return File(path,
System.Net.Mime.MediaTypeNames.Application.Octet,
Path.GetFileName(path));
}
You can add this to your web.config
<location path="your/path/tostaticfiles">
<system.web>
<authorization>
<deny users="?" /> //Denies unauthorized users
</authorization>
</system.web>
</location>
Apart from the location section you also need to indicate IIS that ASP.NET will process these files (runAllManagedModulesForAllRequests="true").
Next to (sibling of system.web node):
<location path="Scripts">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
Under system.webServer node:
<modules runAllManagedModulesForAllRequests="true">
Note: use users="*" instead of users="?" if you don't want to let any user access your files. In my case I did that to prevent access to my JS files and I serve them using bundles.
Related
I'm trying to upload my website onto the web. I have two folders for holding my front-end React files and another for the back-end files that uses Nodejs, cors, and express. It also has my API and middleware.
The front-end pages have already been uploaded onto my IIS and port forwarded with my router, so I can access that anywhere with my IP. But it doesn't function well without my backend files, how can I host the backend files as well and make them work together?
I am getting a headache doing this, does anyone know how to do this??
Thanks in advance.
As far as I know, if you want to host node.js application, you should firstly install the node.exe and the a build of iisnode.
node.exe
iisnode
After installed the IIS nodes, you could set up samples, from the administrative command prompt call %programfiles%\iisnode\setupsamples.bat.
Then you could go to http://localhost/node to see the example.
The next step is to deploy the node.js application inside one iis web application.
Lastly, you should create or modify the web.config to use the iisnode modules.
For example,
<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="app.js" verb="*" modules="iisnode" />
</handlers>
<rewrite>
<rules>
<rule name="mysite">
<match url="/*" />
<action type="Rewrite" url="app.js" />
</rule>
</rules>
</rewrite>
<defaultDocument>
<files>
<add value="app.js" />
</files>
</defaultDocument>
</system.webServer>
More details, you could refer to below article:
https://www.hanselman.com/blog/InstallingAndRunningNodejsApplicationsWithinIISOnWindowsAreYouMad.aspx
In debug mode my code is working fine.
window.BABYLON.SceneLoader.ImportMesh(
"",
"/assets/logo/3D/",
"logo.gltf",
that.scene,
function (meshes) { ..... });
My .gltf 3D asset is stored in public/assets/logo/3D with the name logo.gltf. I am using .NetCore as the web server.
Somehow whenever the loader requests .gltf file, it returns html. It suppose to return json (gltf). Image files like .jpg, '.png', etc... are fine.
I have specify the mime type for .gltf in my web.config file:
<system.webServer>
<staticContent>
<remove fileExtension=".gltf" />
<mimeMap fileExtension=".gltf" mimeType="model/gltf+json" />
</staticContent>
</system.webServer>
Here is the screenshot:
It retrieves as content-type: text/html. It suppose to be model/gltf+json.
How can I load the file safely?
You can configure ASP.NET Core to return correct Content-Type by adding your MIME type to file provider. In Startup add StaticFileOptions argument with extended content type provider to your app.UseStaticFiles() call
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".gltf"] = "model/gltf+json";
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
});
If you want to serve such static files via IIS you need to add a static file processing module before ASP.NET Core pipeline
web.config
<system.webServer>
<handlers>
<!-- added staticGltf handler to serve .gltf files -->
<add name="staticGltf" path="*.gltf" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read" />
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore you_config_here />
<staticContent>
<remove fileExtension=".gltf" />
<mimeMap fileExtension=".gltf" mimeType="model/gltf+json" />
</staticContent>
</system.webServer>
But in this case you might need to address possible issues with routes (such as ASP.NET Core is configured to search files in wwwroot folder but IIS will search in app root instead) and insufficient file permissions.
#Alexander answer is the correct answer. Here is my Startup file if anyone wants to know.
Inside the Configure method:
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".gltf"] = "model/gltf+json";
var staticFileOpt = new StaticFileOptions()
{
ContentTypeProvider = provider
};
app.UseStaticFiles(staticFileOpt);
app.UseSpaStaticFiles(staticFileOpt);
There is UseStaticFiles() and UseSpaStaticFiles(). I am using ReactJS as the SPA framework, that is why I need UseSpaStaticFiles() too.
I have a website and api hosted on IIS 8.5 and lately users of the site are getting the following console error when attempting to POST data to the api when using Microsoft Edge:
HTTP401: DENIED - The requested resource requires user authentication.
(XHR)OPTIONS - http://my-local-address/api/customers/approval/post
Note: Users are authenticated by using Windows Authentication.
This occurs spontaneously and to get around the issue the users are forced to do a hard refresh (Ctrl + F5) on MS Edge and then they can continue with their process. Could there be a setting on IIS that's releasing the user authentication after a period of time?
I've listed my attempts to resolve the issue below:
I've got my organisation to add in a trusted policy for my local web address.
Changed the providers of the API. Moved NTLM above Negotiate.
Removed Negotiate based on this stackoverflow post Windows authentication failing in IIS 7.5.
Try and catch the error from the POST request but I'm returning null every time.
Configured CORS to allow for cross origin.
NB: I'm using angularjs for my front end and ASP.NET Web API 2 for the API.
The following code snippet details how the Web Api is configured:
WebApiConfig.cs
var cors = new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true };
config.EnableCors(cors);
Web.config
<system.web>
<identity impersonate="true" />
<compilation debug="true" targetFramework="4.5.1">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="TRACEVerbHandler" />
<remove name="OPTIONSVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Angular module config using $httpProvider to supply $http requests with credentials
$httpProvider.defaults.withCredentials = true;
I cloned a client's Orchard CMS. The repository that I cloned did not contain the Media folder (this is good). So, a next step was to restore the Media/Default directory from a .zip backup. Now that I've restored that, browsing the to site gives a 404 error for all resources in the Media folder. Why?
Quick Fix
The /Media folder is missing its required Web.config file. Add it.
Media/Web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.web>
<httpHandlers>
<!-- iis6 - for any request in this location, return via managed static file handler -->
<add path="*" verb="*" type="System.Web.StaticFileHandler" />
</httpHandlers>
</system.web>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>
<handlers accessPolicy="Script,Read">
<!--
iis7 - for any request to a file exists on disk, return it via native http module.
accessPolicy 'Script' is to allow for a managed 404 page.
-->
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule" preCondition="integratedMode" resourceType="File" requireAccess="Read" />
</handlers>
</system.webServer>
</configuration>
Details
Out-of-the-box, Orchard's Media folder contains a Web.config file. Since source control excluded the Media folder it also did not have its Web.config. In IIS 7+ Integrated Mode, the following config is required for serving static files, because the root Orchard.Web/Web.config file <clear/>s all handlers.
<add name="StaticFile"
path="*"
verb="*"
modules="StaticFileModule"
preCondition="integratedMode"
resourceType="File"
requireAccess="Read" />
Our Team is building a C# project with a Silverlight module. We deploy to a Windows 2008 with IIS 7. I’m trying to Programmatically Expire the HTTP Response Headers Associated with a Folder called ClientBin immediately. I know how to do it manually through IIS Manager. ( Basically, I go to the HTTP Response Headers Section of the folder or file that is of interest, and then I use "Set Common Headers...." to expire immediately.) However, we will be Redeploying to IIS a number of times, and I want to ensure that it is programmatically done because it’s a headache to keep Reconfiguring all the time.
Should I do it from the C# code of my project or is it better practice to do it using WMI scripting?
#kev and #jeff-cuscutis have provided the ways to configure expiration of the HTTP Response Headers using XML configuration in the web.config file of a ASP.NET application
How to configure static content cache per folder and extension in IIS7?
ou can set specific cache-headers for a whole folder in either your root web.config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- Note the use of the 'location' tag to specify which
folder this applies to-->
<location path="images">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
</staticContent>
</system.webServer>
</location>
</configuration>
Or you can specify these in a web.config file in the content folder:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
</staticContent>
</system.webServer>
</configuration>
I'm not aware of a built in mechanism to target specific file types.
You can do it on a per file basis. Use the path attribute to include the filename
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<location path="YourFileNameHere.xml">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
</configuration>